text string | size int64 | token_count int64 |
|---|---|---|
// Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <ha_test.h>
#include <ha_config.h>
#include <ha_config_parser.h>
#include <query_filter.h>
#include <cc/data.h>
#include <exceptions/exceptions.h>
#include <dhcp/dhcp4.h>
#include <dhcp/dhcp6.h>
#include <dhcp/hwaddr.h>
#include <cstdint>
#include <string>
using namespace isc;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::ha;
using namespace isc::ha::test;
namespace {
/// @brief Test fixture class for @c QueryFilter class.
using QueryFilterTest = HATest;
// This test verifies the case when load balancing is enabled and
// this server is primary.
TEST_F(QueryFilterTest, loadBalancingThisPrimary) {
HAConfigPtr config = createValidConfiguration();
QueryFilter filter(config);
// By default the server1 should serve its own scope only. The
// server2 should serve its scope.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Count number of in scope packets.
unsigned in_scope = 0;
// Set the test size - 65535 queries.
const unsigned queries_num = 65535;
std::string scope_class;
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN));
// If the query is in scope, increase the counter of packets in scope.
if (filter.inScope(query4, scope_class)) {
ASSERT_EQ("HA_server1", scope_class);
ASSERT_NE(scope_class, "HA_server2");
++in_scope;
}
}
// We should have roughly 50/50 split of in scope and out of scope queries.
// However, we don't know exactly how many. To be safe we simply assume that
// we got more than 25% of in scope and more than 25% out of scope queries.
EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4));
EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4));
// Simulate failover scenario.
filter.serveFailoverScopes();
// In the failover case, the server1 should also take responsibility for
// the server2's queries.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Repeat the test, but this time all should be in scope.
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN));
// Every single query mist be in scope.
ASSERT_TRUE(filter.inScope(query4, scope_class));
}
// However, the one that lacks HW address and client id should be out of
// scope.
Pkt4Ptr query4(new Pkt4(DHCPDISCOVER, 1234));
EXPECT_FALSE(filter.inScope(query4, scope_class));
}
// This test verifies that client identifier is used for load balancing.
TEST_F(QueryFilterTest, loadBalancingClientIdThisPrimary) {
HAConfigPtr config = createValidConfiguration();
QueryFilter filter(config);
// By default the server1 should serve its own scope only. The
// server2 should serve its scope.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Fixed HW address used in tests.
std::vector<uint8_t> hw_address(HWAddr::ETHERNET_HWADDR_LEN);
// Count number of in scope packets.
unsigned in_scope = 0;
// Set the test size - 65535 queries.
const unsigned queries_num = 65535;
std::string scope_class;
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random client identifier.
Pkt4Ptr query4 = createQuery4(hw_address, randomKey(8));
// If the query is in scope, increase the counter of packets in scope.
if (filter.inScope(query4, scope_class)) {
ASSERT_EQ("HA_server1", scope_class);
ASSERT_NE(scope_class, "HA_server2");
++in_scope;
}
}
// We should have roughly 50/50 split of in scope and out of scope queries.
// However, we don't know exactly how many. To be safe we simply assume that
// we got more than 25% of in scope and more than 25% out of scope queries.
EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4));
EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4));
// Simulate failover scenario.
filter.serveFailoverScopes();
// In the failover case, the server1 should also take responsibility for
// the server2's queries.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Repeat the test, but this time all should be in scope.
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random client identifier.
Pkt4Ptr query4 = createQuery4(hw_address, randomKey(8));
// Every single query mist be in scope.
ASSERT_TRUE(filter.inScope(query4, scope_class));
}
}
// This test verifies the case when load balancing is enabled and
// this server is secondary.
TEST_F(QueryFilterTest, loadBalancingThisSecondary) {
HAConfigPtr config = createValidConfiguration();
// We're now a secondary server.
config->setThisServerName("server2");
QueryFilter filter(config);
// By default the server2 should serve its own scope only. The
// server1 should serve its scope.
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Count number of in scope packets.
unsigned in_scope = 0;
// Set the test size - 65535 queries.
const unsigned queries_num = 65535;
std::string scope_class;
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN));
// If the query is in scope, increase the counter of packets in scope.
if (filter.inScope(query4, scope_class)) {
ASSERT_EQ("HA_server2", scope_class);
ASSERT_NE(scope_class, "HA_server1");
++in_scope;
}
}
// We should have roughly 50/50 split of in scope and out of scope queries.
// However, we don't know exactly how many. To be safe we simply assume that
// we got more than 25% of in scope and more than 25% out of scope queries.
EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4));
EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4));
// Simulate failover scenario.
filter.serveFailoverScopes();
// In this scenario, the server1 died, so the server2 should now serve
// both scopes.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Repeat the test, but this time all should be in scope.
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN));
// Every single query must be in scope.
ASSERT_TRUE(filter.inScope(query4, scope_class));
}
}
// This test verifies the case when load balancing is enabled and
// this server is backup.
/// @todo Expand these tests once we implement the actual load balancing to
/// verify which packets are in scope.
TEST_F(QueryFilterTest, loadBalancingThisBackup) {
HAConfigPtr config = createValidConfiguration();
config->setThisServerName("server3");
QueryFilter filter(config);
// The backup server doesn't handle any DHCP traffic by default.
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Set the test size - 65535 queries.
const unsigned queries_num = 65535;
std::string scope_class;
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN));
// None of the packets should be handlded by the backup server.
ASSERT_FALSE(filter.inScope(query4, scope_class));
}
// Simulate failover. Although, backup server never starts handling
// other server's traffic automatically, it can be manually instructed
// to do so. This simulates such scenario.
filter.serveFailoverScopes();
// The backup server now handles traffic of server 1 and server 2.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Repeat the test, but this time all should be in scope.
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt4Ptr query4 = createQuery4(randomKey(HWAddr::ETHERNET_HWADDR_LEN));
// Every single query must be in scope.
ASSERT_TRUE(filter.inScope(query4, scope_class));
}
}
// This test verifies the case when hot-standby is enabled and this
// server is primary.
TEST_F(QueryFilterTest, hotStandbyThisPrimary) {
HAConfigPtr config = createValidConfiguration();
config->setHAMode("hot-standby");
config->getPeerConfig("server2")->setRole("standby");
QueryFilter filter(config);
Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66");
// By default, only the primary server is active.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
std::string scope_class;
// It should process its queries.
EXPECT_TRUE(filter.inScope(query4, scope_class));
// Simulate failover scenario, in which the active server detects a
// failure of the standby server. This doesn't change anything in how
// the traffic is distributed.
filter.serveFailoverScopes();
// The server1 continues to process its own traffic.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
EXPECT_TRUE(filter.inScope(query4, scope_class));
EXPECT_EQ("HA_server1", scope_class);
EXPECT_NE(scope_class, "HA_server2");
}
// This test verifies the case when hot-standby is enabled and this
// server is standby.
TEST_F(QueryFilterTest, hotStandbyThisSecondary) {
HAConfigPtr config = createValidConfiguration();
config->setHAMode("hot-standby");
config->getPeerConfig("server2")->setRole("standby");
config->setThisServerName("server2");
QueryFilter filter(config);
Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66");
// The server2 doesn't process any queries by default. The whole
// traffic is processed by the server1.
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
std::string scope_class;
EXPECT_FALSE(filter.inScope(query4, scope_class));
EXPECT_EQ("HA_server1", scope_class);
EXPECT_NE(scope_class, "HA_server2");
// Simulate failover case whereby the standby server detects a
// failure of the active server.
filter.serveFailoverScopes();
// The server2 now handles the traffic normally handled by the
// server1.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
EXPECT_TRUE(filter.inScope(query4, scope_class));
EXPECT_EQ("HA_server1", scope_class);
EXPECT_NE(scope_class, "HA_server2");
}
// This test verifies the case when hot-standby is enabled and this
// server is backup.
TEST_F(QueryFilterTest, hotStandbyThisBackup) {
HAConfigPtr config = createValidConfiguration();
config->setHAMode("hot-standby");
config->getPeerConfig("server2")->setRole("standby");
config->setThisServerName("server3");
QueryFilter filter(config);
Pkt4Ptr query4 = createQuery4("11:22:33:44:55:66");
// By default the backup server doesn't process any traffic.
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
std::string scope_class;
EXPECT_FALSE(filter.inScope(query4, scope_class));
// Simulate failover. Although, backup server never starts handling
// other server's traffic automatically, it can be manually instructed
// to do so. This simulates such scenario.
filter.serveFailoverScopes();
// The backup server now handles the entire traffic, i.e. the traffic
// that the primary server handles.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
EXPECT_TRUE(filter.inScope(query4, scope_class));
}
// This test verifies the case when load balancing is enabled and
// this DHCPv6 server is primary.
TEST_F(QueryFilterTest, loadBalancingThisPrimary6) {
HAConfigPtr config = createValidConfiguration();
QueryFilter filter(config);
// By default the server1 should serve its own scope only. The
// server2 should serve its scope.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Count number of in scope packets.
unsigned in_scope = 0;
// Set the test size - 65535 queries.
const unsigned queries_num = 65535;
std::string scope_class;
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random DUID.
Pkt6Ptr query6 = createQuery6(randomKey(10));
// If the query is in scope, increase the counter of packets in scope.
if (filter.inScope(query6, scope_class)) {
ASSERT_EQ("HA_server1", scope_class);
ASSERT_NE(scope_class, "HA_server2");
++in_scope;
}
}
// We should have roughly 50/50 split of in scope and out of scope queries.
// However, we don't know exactly how many. To be safe we simply assume that
// we got more than 25% of in scope and more than 25% out of scope queries.
EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4));
EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4));
// Simulate failover scenario.
filter.serveFailoverScopes();
// In the failover case, the server1 should also take responsibility for
// the server2's queries.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Repeat the test, but this time all should be in scope.
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt6Ptr query6 = createQuery6(randomKey(10));
// Every single query mist be in scope.
ASSERT_TRUE(filter.inScope(query6, scope_class));
}
// However, the one that lacks DUID should be out of scope.
Pkt6Ptr query6(new Pkt6(DHCPV6_SOLICIT, 1234));
EXPECT_FALSE(filter.inScope(query6, scope_class));
}
// This test verifies the case when load balancing is enabled and
// this server is secondary.
TEST_F(QueryFilterTest, loadBalancingThisSecondary6) {
HAConfigPtr config = createValidConfiguration();
// We're now a secondary server.
config->setThisServerName("server2");
QueryFilter filter(config);
// By default the server2 should serve its own scope only. The
// server1 should serve its scope.
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Count number of in scope packets.
unsigned in_scope = 0;
// Set the test size - 65535 queries.
const unsigned queries_num = 65535;
std::string scope_class;
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt6Ptr query6 = createQuery6(randomKey(10));
// If the query is in scope, increase the counter of packets in scope.
if (filter.inScope(query6, scope_class)) {
ASSERT_EQ("HA_server2", scope_class);
ASSERT_NE(scope_class, "HA_server1");
++in_scope;
}
}
// We should have roughly 50/50 split of in scope and out of scope queries.
// However, we don't know exactly how many. To be safe we simply assume that
// we got more than 25% of in scope and more than 25% out of scope queries.
EXPECT_GT(in_scope, static_cast<unsigned>(queries_num / 4));
EXPECT_GT(queries_num - in_scope, static_cast<unsigned>(queries_num / 4));
// Simulate failover scenario.
filter.serveFailoverScopes();
// In this scenario, the server1 died, so the server2 should now serve
// both scopes.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Repeat the test, but this time all should be in scope.
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt6Ptr query6 = createQuery6(randomKey(HWAddr::ETHERNET_HWADDR_LEN));
// Every single query must be in scope.
ASSERT_TRUE(filter.inScope(query6, scope_class));
}
}
// This test verifies the case when load balancing is enabled and
// this server is backup.
/// @todo Expand these tests once we implement the actual load balancing to
/// verify which packets are in scope.
TEST_F(QueryFilterTest, loadBalancingThisBackup6) {
HAConfigPtr config = createValidConfiguration();
config->setThisServerName("server3");
QueryFilter filter(config);
// The backup server doesn't handle any DHCP traffic by default.
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Set the test size - 65535 queries.
const unsigned queries_num = 65535;
std::string scope_class;
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt6Ptr query6 = createQuery6(randomKey(10));
// None of the packets should be handlded by the backup server.
ASSERT_FALSE(filter.inScope(query6, scope_class));
}
// Simulate failover. Although, backup server never starts handling
// other server's traffic automatically, it can be manually instructed
// to do so. This simulates such scenario.
filter.serveFailoverScopes();
// The backup server now handles traffic of server 1 and server 2.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Repeat the test, but this time all should be in scope.
for (unsigned i = 0; i < queries_num; ++i) {
// Create query with random HW address.
Pkt6Ptr query6 = createQuery6(randomKey(10));
// Every single query must be in scope.
ASSERT_TRUE(filter.inScope(query6, scope_class));
}
}
// This test verifies the case when hot-standby is enabled and this
// server is primary.
TEST_F(QueryFilterTest, hotStandbyThisPrimary6) {
HAConfigPtr config = createValidConfiguration();
config->setHAMode("hot-standby");
config->getPeerConfig("server2")->setRole("standby");
QueryFilter filter(config);
Pkt6Ptr query6 = createQuery6("01:02:11:22:33:44:55:66");
// By default, only the primary server is active.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
std::string scope_class;
// It should process its queries.
EXPECT_TRUE(filter.inScope(query6, scope_class));
// Simulate failover scenario, in which the active server detects a
// failure of the standby server. This doesn't change anything in how
// the traffic is distributed.
filter.serveFailoverScopes();
// The server1 continues to process its own traffic.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
EXPECT_TRUE(filter.inScope(query6, scope_class));
EXPECT_EQ("HA_server1", scope_class);
EXPECT_NE(scope_class, "HA_server2");
}
// This test verifies the case when hot-standby is enabled and this
// server is standby.
TEST_F(QueryFilterTest, hotStandbyThisSecondary6) {
HAConfigPtr config = createValidConfiguration();
config->setHAMode("hot-standby");
config->getPeerConfig("server2")->setRole("standby");
config->setThisServerName("server2");
QueryFilter filter(config);
Pkt6Ptr query6 = createQuery6("01:02:11:22:33:44:55:66");
// The server2 doesn't process any queries by default. The whole
// traffic is processed by the server1.
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
std::string scope_class;
EXPECT_FALSE(filter.inScope(query6, scope_class));
EXPECT_EQ("HA_server1", scope_class);
EXPECT_NE(scope_class, "HA_server2");
// Simulate failover case whereby the standby server detects a
// failure of the active server.
filter.serveFailoverScopes();
// The server2 now handles the traffic normally handled by the
// server1.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
EXPECT_TRUE(filter.inScope(query6, scope_class));
EXPECT_EQ("HA_server1", scope_class);
EXPECT_NE(scope_class, "HA_server2");
}
// This test verifies that it is possible to explicitly enable and
// disable certain scopes.
TEST_F(QueryFilterTest, explicitlyServeScopes) {
HAConfigPtr config = createValidConfiguration();
QueryFilter filter(config);
// Initially, the scopes should be set according to the load
// balancing configuration.
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Enable "server2" scope.
ASSERT_NO_THROW(filter.serveScope("server2"));
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Enable only "server2" scope.
ASSERT_NO_THROW(filter.serveScopeOnly("server2"));
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_TRUE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Explicitly enable selected scopes.
ASSERT_NO_THROW(filter.serveScopes({ "server1", "server3" }));
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_TRUE(filter.amServingScope("server3"));
// Revert to defaults.
ASSERT_NO_THROW(filter.serveDefaultScopes());
EXPECT_TRUE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Disable all scopes.
ASSERT_NO_THROW(filter.serveNoScopes());
EXPECT_FALSE(filter.amServingScope("server1"));
EXPECT_FALSE(filter.amServingScope("server2"));
EXPECT_FALSE(filter.amServingScope("server3"));
// Test negative cases.
EXPECT_THROW(filter.serveScope("unsupported"), BadValue);
EXPECT_THROW(filter.serveScopeOnly("unsupported"), BadValue);
EXPECT_THROW(filter.serveScopes({ "server1", "unsupported" }), BadValue);
}
}
| 24,455 | 7,872 |
#include <lowletorfeats/base/FeatureKey.hpp>
int main()
{
// Test constructors
lowletorfeats::base::FeatureKey fKey;
fKey = lowletorfeats::base::FeatureKey(fKey);
fKey = lowletorfeats::base::FeatureKey("invalid.invalid.invalid");
fKey = lowletorfeats::base::FeatureKey("invalid", "invalid", "invalid");
fKey = lowletorfeats::base::FeatureKey("tfidf", "tfidf", "full");
// Test public methods
fKey.changeKey("okapi.bm25.body");
fKey.toString();
fKey.toHash();
fKey.getFType();
fKey.getFName();
fKey.getFSection();
fKey.getVType();
fKey.getVName();
fKey.getVSection();
return 0;
}
| 651 | 242 |
#ifndef __ET_LOG_HANDLER__
#define __ET_LOG_HANDLER__
#include "Headers.hpp"
namespace et {
class LogHandler {
public:
static el::Configurations setupLogHandler(int *argc, char ***argv);
static void setupLogFile(el::Configurations *defaultConf, string filename,
string maxlogsize = "20971520");
static void rolloutHandler(const char *filename, std::size_t size);
static string stderrToFile(const string &pathPrefix);
};
} // namespace et
#endif // __ET_LOG_HANDLER__
| 507 | 168 |
/**
* @file src/llvmir2hll/graphs/cfg/cfg_traversals/var_use_cfg_traversal.cpp
* @brief Implementation of VarUseCFGTraversal.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/llvmir2hll/analysis/value_analysis.h"
#include "retdec/llvmir2hll/graphs/cfg/cfg_traversals/var_use_cfg_traversal.h"
#include "retdec/llvmir2hll/ir/statement.h"
#include "retdec/llvmir2hll/support/debug.h"
namespace retdec {
namespace llvmir2hll {
/**
* @brief Constructs a new traverser.
*
* See the description of isDefinedPriorToEveryAccess() for information on the
* parameters.
*/
VarUseCFGTraversal::VarUseCFGTraversal(ShPtr<Variable> var,
ShPtr<CFG> cfg, ShPtr<ValueAnalysis> va):
CFGTraversal(cfg, true), var(var), va(va) {}
/**
* @brief Returns @c true if the given variable @a var is defined/modified prior
* to every read access to it in @a cfg.
*
* @param[in] var Variable whose definition/modification is looked for.
* @param[in] cfg CFG that should be traversed.
* @param[in] va Analysis of values.
*
* @par Preconditions
* - @a var, @a cfg, and @a va are non-null
* - @a va is in a valid state
*
* This function leaves @a va in a valid state.
*/
bool VarUseCFGTraversal::isDefinedPriorToEveryAccess(ShPtr<Variable> var,
ShPtr<CFG> cfg, ShPtr<ValueAnalysis> va) {
PRECONDITION_NON_NULL(var);
PRECONDITION_NON_NULL(cfg);
PRECONDITION_NON_NULL(va);
PRECONDITION(va->isInValidState(), "it is not in a valid state");
ShPtr<VarUseCFGTraversal> traverser(new VarUseCFGTraversal(var, cfg, va));
// Obtain the first statement of the function. We have to skip the entry
// node because there are no statements corresponding to the VarDefStmts
// for function parameters.
ShPtr<CFG::Node> funcBodyNode((*cfg->getEntryNode()->succ_begin())->getDst());
ShPtr<Statement> firstStmt(*funcBodyNode->stmt_begin());
return traverser->performTraversal(firstStmt);
}
bool VarUseCFGTraversal::visitStmt(ShPtr<Statement> stmt) {
ShPtr<ValueData> stmtData(va->getValueData(stmt));
/* TODO Include the following restriction?
// There should not be any function calls.
if (stmtData->hasCalls()) {
return false;
}
*/
// Check whether the variable is read prior modifying; if so, we are done.
if (stmtData->isDirRead(var) || stmtData->mayBeIndirRead(var) ||
stmtData->mustBeIndirRead(var)) {
currRetVal = false;
return false;
}
// Check whether we are modifying the variable. Here, it doesn't suffice
// that the variable may be read -- it either has to be read directly or
// must be read indirectly.
if (stmtData->isDirWritten(var) || stmtData->mustBeIndirWritten(var)) {
currRetVal = true;
return false;
}
return true;
}
bool VarUseCFGTraversal::getEndRetVal() const {
return true;
}
bool VarUseCFGTraversal::combineRetVals(bool origRetVal, bool newRetVal) const {
return origRetVal ? newRetVal : false;
}
} // namespace llvmir2hll
} // namespace retdec
| 2,929 | 1,071 |
#include<iostream>
#include<Mystring.h>
#include<string.h>
#include<stdio.h>
using namespace std;
MyString::MyString(){
//无参构成一个空串
m_len=0;
m_p=new char[m_len+1];
strcpy(m_p,"");
}
MyString::MyString(const char *p){
if(p==NULL){
m_len=0;
m_p=new char[m_len+1];
strcpy(m_p,"");
}else{
m_len=strlen(p);
m_p=new char[m_len+1];
strcpy(m_p,p);
}
}
//拷贝构造函数。
MyString::MyString(const MyString& s){
m_len=s.m_len;
m_p=new char[m_len+1];
strcpy(m_p,s.m_p);
}
MyString::~MyString(){
if(m_p!=NULL){
delete [] m_p;
m_p = NULL;
m_len = 0;
}
}
void MyString::printCom(){
cout<<"m_len:"<<m_len<<endl;
cout<<"m_p:"<<endl;
cout<< m_p<<endl;
}
MyString& MyString::operator=(const char *p){
if(p!=NULL){
m_len =strlen(p);
cout<<"hhhh"<<endl;
m_p = new char[strlen(p)+1];
strcpy(m_p,p);
} else{
m_len=0;
m_p =new char[strlen(p)+1];
strcpy(m_p,"");
}
return *this;
}
MyString& MyString::operator=(const MyString& s){
m_len = s.m_len;
cout<<"dhdhfh"<<endl;
m_p = new char[strlen(s.m_p)+1];
strcpy(m_p,s.m_p);
return *this;
}
char& MyString:: operator[]( int i){
return m_p[i];
}
ostream& operator <<(ostream& out, MyString& s){
out<<"m_len:"<<s.m_len<<endl;
out<<"*m_p:"<<s.m_p<<endl;
return out;
}
istream& operator >>(istream& in, MyString& s){
in>>s.m_len;
return in;
}
| 1,686 | 851 |
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_VIEWS_FILTER_VIEW_HPP
#define STAPL_VIEWS_FILTER_VIEW_HPP
#include <stapl/views/core_view.hpp>
#include <stapl/views/operations/sequence.hpp>
#include <stapl/views/operations/view_iterator.hpp>
#include <stapl/algorithms/algorithm.hpp>
#include <iostream>
#define INFINITE std::numeric_limits<size_type>::max()
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Default functor that accepts everything
//////////////////////////////////////////////////////////////////////
struct tautology
{
typedef bool result_type;
template <typename T>
bool operator()(T) { return true; }
};
//////////////////////////////////////////////////////////////////////
/// @brief Defines a filter view over the specified @p View.
///
/// This view provides a selective traversal over the elements
/// referenced for the specified view.
/// @ingroup filter_view
//////////////////////////////////////////////////////////////////////
template <typename View, typename Pred>
class filter_view :
public core_view<typename View::view_container_type,
typename View::domain_type,
typename View::map_func_type>
{
typedef core_view<typename View::view_container_type,
typename View::domain_type,
typename View::map_func_type> base_type;
protected:
Pred m_pred;
mutable typename base_type::size_type m_size;
public:
typedef typename View::view_container_type view_container_type;
typedef view_container_type container_type;
typedef typename view_container_type::reference reference;
typedef typename view_container_type::const_reference const_reference;
typedef typename View::domain_type domain_type;
typedef typename View::map_func_type map_func_type;
typedef map_func_type map_function;
typedef typename view_container_type::value_type value_type;
typedef typename domain_type::index_type index_type;
typedef typename base_type::size_type size_type;
typedef index_iterator<filter_view> iterator;
typedef const_index_iterator<filter_view> const_iterator;
//////////////////////////////////////////////////////////////////////
/// @brief Constructs a filter view over the given @p view.
///
/// @param view View to filter
/// @param pred Functor used to filter elements
//////////////////////////////////////////////////////////////////////
filter_view(View const& view, Pred const& pred)
: base_type(view.container(), view.domain(), view.mapfunc()),
m_pred(pred),
m_size(INFINITE)
{ }
//////////////////////////////////////////////////////////////////////
/// @brief Constructor used to pass ownership of the container to the view.
///
/// @param vcont Pointer to the container used to forward the operations.
/// @param dom Domain to be used by the view.
/// @param mfunc Mapping function to transform view indices to container
/// gids.
/// @param pred Functor used to filter elements
//////////////////////////////////////////////////////////////////////
filter_view(view_container_type* vcont, domain_type const& dom,
map_func_type mfunc=map_func_type(), Pred const& pred=Pred())
: base_type(vcont, dom, mfunc),
m_pred(pred),
m_size(INFINITE)
{ }
//////////////////////////////////////////////////////////////////////
/// @brief Constructor that does not takes ownership over the passed
/// container.
///
/// @param vcont Reference to the container used to forward the operations.
/// @param dom Domain to be used by the view.
/// @param mfunc Mapping function to transform view indices to container
/// gids.
/// @param pred Functor used to filter elements
//////////////////////////////////////////////////////////////////////
filter_view(view_container_type const& vcont, domain_type const& dom,
map_func_type mfunc=map_func_type(), Pred const& pred=Pred())
: base_type(vcont, dom, mfunc),
m_pred(pred),
m_size(INFINITE)
{ }
filter_view(view_container_type const& vcont, domain_type const& dom,
map_func_type mfunc, filter_view const& other)
: base_type(vcont, dom, mfunc),
m_pred(other.m_pred),
m_size(other.m_size)
{ }
//////////////////////////////////////////////////////////////////////
/// @brief Constructor that does not takes ownership over the passed
/// container.
///
/// @param other View to copy from.
//////////////////////////////////////////////////////////////////////
filter_view(filter_view const& other)
: base_type(other),
m_pred(other.m_pred),
m_size(other.m_size)
{ }
/// @name Sequence Iterator
/// @warning Methods in the Sequence Iterator group should only be used
/// inside a work function which is processing a segmented view.
/// These functions will perform a read operation on the data,
/// which is not how iterators normally work
/// @{
//////////////////////////////////////////////////////////////////////
/// @brief Return an iterator over the element whose GID is the
/// first valid index, based on applying the predicate
/// to the element value
//////////////////////////////////////////////////////////////////////
iterator begin(void)
{
index_type index = this->domain().first();
if (m_pred(this->container().get_element(this->mapfunc()(index))))
return iterator(*this,index);
else
return iterator(*this,this->next(index));
}
//////////////////////////////////////////////////////////////////////
/// @brief Return an iterator over the element whose GID is the
/// first valid index, based on applying the predicate
/// to the element value
//////////////////////////////////////////////////////////////////////
const_iterator begin(void) const
{
index_type index = this->domain().first();
if (m_pred(this->container().get_element(this->mapfunc()(index))))
return const_iterator(*this,index);
else
return const_iterator(*this,this->next(index));
}
//////////////////////////////////////////////////////////////////////
/// @brief Return an iterator over the element whose GID is the
/// last valid index, based on applying the predicate
/// to the element value
//////////////////////////////////////////////////////////////////////
iterator end(void)
{
index_type index = this->domain().advance(this->domain().last(),1);
return iterator(*this,index);
}
//////////////////////////////////////////////////////////////////////
/// @brief Return an iterator over the element whose GID is the
/// last valid index, based on applying the predicate
/// to the element value
//////////////////////////////////////////////////////////////////////
const_iterator end(void) const
{
index_type index = this->domain().advance(this->domain().last(),1);
return const_iterator(*this,index);
}
//////////////////////////////////////////////////////////////////////
/// @brief Return an iterator over the element whose GID is the
/// next valid index, based on applying the predicate
/// to the element value
//////////////////////////////////////////////////////////////////////
index_type next(index_type index) const
{
index_type next_index = this->domain().advance(index,1);
while (!m_pred(this->container().get_element(this->mapfunc()(next_index)))
&& this->domain().contains(next_index)) {
next_index = this->domain().advance(next_index,1);
}
return next_index;
}
/// @}
//////////////////////////////////////////////////////////////////////
/// @brief Returns value at the specified @p index.
//////////////////////////////////////////////////////////////////////
value_type get_element(index_type index)
{
return this->container().get_element(this->mapfunc()(index));
}
//////////////////////////////////////////////////////////////////////
/// @brief Returns the predicate used to filter the values.
//////////////////////////////////////////////////////////////////////
Pred const& predicate(void) const
{
return m_pred;
}
//////////////////////////////////////////////////////////////////////
/// @brief Return the number of elements referenced for the view.
//////////////////////////////////////////////////////////////////////
size_type size(void) const
{
if (m_size==INFINITE) {
View orig(this->container(), this->domain(), this->mapfunc());
m_size = count_if(orig, m_pred);
}
return m_size;
}
//////////////////////////////////////////////////////////////////////
/// @internal
/// @brief use to examine this class
/// @param msg your message (to provide context)
//////////////////////////////////////////////////////////////////////
void debug(char *msg=0)
{
std::cerr << "FILTER_VIEW " << this << " : ";
if (msg) {
std::cerr << msg;
}
std::cerr << std::endl;
base_type::debug();
}
}; //class filter_view
template<typename View, typename Pred>
struct view_traits<filter_view<View,Pred> >
{
typedef typename view_traits<View>::value_type value_type;
typedef typename view_traits<View>::reference reference;
typedef typename view_traits<View>::container container;
typedef typename view_traits<View>::map_function map_function;
typedef typename view_traits<View>::domain_type domain_type;
typedef typename domain_type::index_type index_type;
};
template<typename View,
typename Pred,
typename Info,
typename CID>
struct localized_view<mix_view<filter_view<View,Pred>,Info,CID>>
: public filter_view<typename cast_container_view<View,
typename mix_view<filter_view<View,Pred>,
Info, CID>::component_type>::type,Pred>
{
typedef mix_view<filter_view<View,Pred>,Info,CID> view_base_type;
typedef typename mix_view<filter_view<View,Pred>,
Info,CID>::component_type component_type;
typedef typename cast_container_view<View,
component_type>::type casted_view_type;
typedef filter_view<casted_view_type,Pred> base_type;
localized_view(view_base_type const& v)
: base_type(casted_view_type(*(v.get_component()), v.domain(),
v.mapfunc()), v.predicate())
{ }
};
template<typename View, typename Pred>
filter_view<View,Pred>
filter(View const& view, Pred const& pred)
{
return filter_view<View,Pred>(view, pred);
}
} // namespace stapl
#undef INFINITE
#endif /* STAPL_VIEWS_FILTER_VIEW_HPP */
| 11,454 | 2,987 |
/*********************************************************************
Copyright 2013 Karl Jones
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.
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.
For Further Information Please Contact me at
Karljj1@yahoo.com
http://p.sf.net/kdis/UserGuide
*********************************************************************/
#include "./GED_EnhancedGroundCombatSoldier.h"
using namespace KDIS;
using namespace DATA_TYPE;
using namespace ENUMS;
//////////////////////////////////////////////////////////////////////////
// Public:
//////////////////////////////////////////////////////////////////////////
GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier() :
m_ui8WaterStatus( 0 ),
m_ui8RestStatus( 0 ),
m_ui8PriAmmun( 0 ),
m_ui8SecAmmun( 0 )
{
}
//////////////////////////////////////////////////////////////////////////
GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( KDataStream & stream )
{
Decode( stream );
}
//////////////////////////////////////////////////////////////////////////
GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( KUINT16 ID, KINT16 XOffset, KINT16 YOffset, KINT16 ZOffset, const EntityAppearance & EA,
KINT8 Psi, KINT8 Theta, KINT8 Phi, KINT8 Speed, KINT8 HeadAzimuth, KINT8 HeadElevation,
KINT8 HeadScanRate, KINT8 HeadElevationRate, KUINT8 WaterStatus, RestStatus R,
KUINT8 PrimaryAmmunition, KUINT8 SecondaryAmmunition ) :
GED_BasicGroundCombatSoldier( ID, XOffset, YOffset, ZOffset, EA, Psi, Theta, Phi, Speed,
HeadAzimuth, HeadElevation, HeadScanRate, HeadElevationRate ),
m_ui8WaterStatus( WaterStatus ),
m_ui8RestStatus( R ),
m_ui8PriAmmun( PrimaryAmmunition ),
m_ui8SecAmmun( SecondaryAmmunition )
{
}
//////////////////////////////////////////////////////////////////////////
GED_EnhancedGroundCombatSoldier::GED_EnhancedGroundCombatSoldier( const GED_BasicGroundCombatSoldier & BGCS, KUINT8 WaterStatus, RestStatus R,
KUINT8 PrimaryAmmunition, KUINT8 SecondaryAmmunition ) :
GED_BasicGroundCombatSoldier( BGCS ),
m_ui8WaterStatus( WaterStatus ),
m_ui8RestStatus( R ),
m_ui8PriAmmun( PrimaryAmmunition ),
m_ui8SecAmmun( SecondaryAmmunition )
{
}
//////////////////////////////////////////////////////////////////////////
GED_EnhancedGroundCombatSoldier::~GED_EnhancedGroundCombatSoldier()
{
}
//////////////////////////////////////////////////////////////////////////
GroupedEntityCategory GED_EnhancedGroundCombatSoldier::GetGroupedEntityCategory() const
{
return EnhancedGroundCombatSoldierGEC;
}
//////////////////////////////////////////////////////////////////////////
KUINT8 GED_EnhancedGroundCombatSoldier::GetLength() const
{
return GED_ENHANCED_GROUND_COMBAT_SOLDIER_SIZE;
}
//////////////////////////////////////////////////////////////////////////
void GED_EnhancedGroundCombatSoldier::SetWaterStatus( KUINT8 W )
{
m_ui8WaterStatus = W;
}
//////////////////////////////////////////////////////////////////////////
KUINT8 GED_EnhancedGroundCombatSoldier::GetWaterStatus() const
{
return m_ui8WaterStatus;
}
//////////////////////////////////////////////////////////////////////////
void GED_EnhancedGroundCombatSoldier::SetRestStatus( RestStatus R )
{
m_ui8RestStatus = R;
}
//////////////////////////////////////////////////////////////////////////
RestStatus GED_EnhancedGroundCombatSoldier::GetRestStatus() const
{
return ( RestStatus )m_ui8RestStatus;
}
//////////////////////////////////////////////////////////////////////////
void GED_EnhancedGroundCombatSoldier::SetPrimaryAmmunition( KUINT8 P )
{
m_ui8PriAmmun = P;
}
//////////////////////////////////////////////////////////////////////////
KUINT8 GED_EnhancedGroundCombatSoldier::GetPrimaryAmmunition() const
{
return m_ui8PriAmmun;
}
//////////////////////////////////////////////////////////////////////////
void GED_EnhancedGroundCombatSoldier::SetSecondaryAmmunition( KUINT8 S )
{
m_ui8SecAmmun = S;
}
//////////////////////////////////////////////////////////////////////////
KUINT8 GED_EnhancedGroundCombatSoldier::GetSecondaryAmmunition() const
{
return m_ui8SecAmmun;
}
//////////////////////////////////////////////////////////////////////////
KString GED_EnhancedGroundCombatSoldier::GetAsString() const
{
KStringStream ss;
ss << GED_BasicGroundCombatSoldier::GetAsString();
ss << "GED Enhanced Ground Combat Vehicle\n"
<< "\tWater Status: " << ( KUINT16 )m_ui8WaterStatus << " ounce/s\n"
<< "\tRest Status: " << GetEnumAsStringRestStatus( m_ui8RestStatus ) << "\n"
<< "\tPrimary Ammunition: " << ( KUINT16 )m_ui8PriAmmun << "\n"
<< "\tSecondary Ammunition: " << ( KUINT16 )m_ui8SecAmmun << "\n";
return ss.str();
}
//////////////////////////////////////////////////////////////////////////
void GED_EnhancedGroundCombatSoldier::Decode( KDataStream & stream )
{
if( stream.GetBufferSize() < GED_ENHANCED_GROUND_COMBAT_SOLDIER_SIZE )throw KException( __FUNCTION__, NOT_ENOUGH_DATA_IN_BUFFER );
GED_BasicGroundCombatSoldier::Decode( stream );
stream >> m_ui8WaterStatus
>> m_ui8RestStatus
>> m_ui8PriAmmun
>> m_ui8SecAmmun;
}
//////////////////////////////////////////////////////////////////////////
KDataStream GED_EnhancedGroundCombatSoldier::Encode() const
{
KDataStream stream;
GED_EnhancedGroundCombatSoldier::Encode( stream );
return stream;
}
//////////////////////////////////////////////////////////////////////////
void GED_EnhancedGroundCombatSoldier::Encode( KDataStream & stream ) const
{
GED_BasicGroundCombatSoldier::Encode( stream );
stream << m_ui8WaterStatus
<< m_ui8RestStatus
<< m_ui8PriAmmun
<< m_ui8SecAmmun;
}
//////////////////////////////////////////////////////////////////////////
KBOOL GED_EnhancedGroundCombatSoldier::operator == ( const GED_EnhancedGroundCombatSoldier & Value ) const
{
if( GED_BasicGroundCombatSoldier::operator!=( Value ) ) return false;
if( m_ui8WaterStatus != Value.m_ui8WaterStatus ) return false;
if( m_ui8RestStatus != Value.m_ui8RestStatus ) return false;
if( m_ui8PriAmmun != Value.m_ui8PriAmmun ) return false;
if( m_ui8SecAmmun != Value.m_ui8SecAmmun ) return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
KBOOL GED_EnhancedGroundCombatSoldier::operator != ( const GED_EnhancedGroundCombatSoldier & Value ) const
{
return !( *this == Value );
}
//////////////////////////////////////////////////////////////////////////
| 8,008 | 2,550 |
#include "Cappuccino/Mesh.h"
#include "Cappuccino/CappMacros.h"
#include "Cappuccino/ResourceManager.h"
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
using string = std::string;
namespace Cappuccino {
struct FaceData {
unsigned vertexData[3]{};
unsigned textureData[3]{};
unsigned normalData[3]{};
};
std::string Mesh::_meshDirectory = "./Assets/Meshes/";
Mesh::Mesh(const std::string& name, const std::string& path) :
_path(path), _name(name) {}
Mesh::~Mesh() {
glDeleteVertexArrays(1, &_VAO);
}
Mesh::Mesh(const std::vector<float>& VERTS, const std::vector<float>& TEXTS, const std::vector<float>& NORMS, const std::vector<float>& TANGS)
{
verts = VERTS;
texts = TEXTS;
norms = NORMS;
tangs = TANGS;
}
Mesh::Mesh(Mesh& other)
{
verts = other.verts;
texts = other.texts;
norms = other.norms;
tangs = other.tangs;
_numVerts = other._numVerts;
_numFaces = other._numFaces;
}
bool Mesh::loadMesh()
{
if (loaded)
return true;
char inputString[128];
std::vector<glm::vec3> vertexData{};
std::vector<glm::vec2> textureData{};
std::vector<glm::vec3> normalData{};
std::vector<FaceData> faces{};
std::vector<float> unPvertexData{};
std::vector<float> unPtextureData{};
std::vector<float> unPnormalData{};
//load the file
std::ifstream input{};
input.open(_meshDirectory + _path);
if (!input.good()) {
std::cout << "Problem loading file: " << _path << "\n";
return false;
}
//import data
while (!input.eof()) {
input.getline(inputString, 128);
//vertex data
if (inputString[0] == 'v' && inputString[1] == ' ') {
glm::vec3 vertData{ 0,0,0 };
std::sscanf(inputString, "v %f %f %f", &vertData.x, &vertData.y, &vertData.z);
vertexData.push_back(vertData);
}//texture data
else if (inputString[0] == 'v' && inputString[1] == 't') {
glm::vec2 texCoord{ 0,0 };
std::sscanf(inputString, "vt %f %f", &texCoord.x, &texCoord.y);
textureData.push_back(texCoord);
}//normal data
else if (inputString[0] == 'v' && inputString[1] == 'n') {
glm::vec3 normData{ 0,0,0 };
std::sscanf(inputString, "vn %f %f %f", &normData.x, &normData.y, &normData.z);
normalData.push_back(normData);
}//face data
else if (inputString[0] == 'f' && inputString[1] == ' ') {
faces.emplace_back();
std::sscanf(inputString, "f %u/%u/%u %u/%u/%u %u/%u/%u",
&faces.back().vertexData[0], &faces.back().textureData[0], &faces.back().normalData[0],
&faces.back().vertexData[1], &faces.back().textureData[1], &faces.back().normalData[1],
&faces.back().vertexData[2], &faces.back().textureData[2], &faces.back().normalData[2]);
}
else
continue;
}
//add the data to the vectors
for (unsigned i = 0; i < faces.size(); i++) {
for (unsigned j = 0; j < 3; j++) {
unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].x);
unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].y);
unPvertexData.push_back(vertexData[faces[i].vertexData[j] - 1].z);
if (!textureData.empty()) {
unPtextureData.push_back(textureData[faces[i].textureData[j] - 1].x);
unPtextureData.push_back(textureData[faces[i].textureData[j] - 1].y);
}
if (!normalData.empty()) {
unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].x);
unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].y);
unPnormalData.push_back(normalData[faces[i].normalData[j] - 1].z);
}
}
}
_numFaces = faces.size();
_numVerts = _numFaces * 3;
//https://learnopengl.com/Advanced-Lighting/Normal-Mapping
//https://gitlab.com/ShawnM427/florp/blob/master/src/florp/graphics/MeshBuilder.cpp
//it works!
std::vector<glm::vec3> tangs;
for (unsigned i = 0; i < _numFaces; i++) {
std::vector<glm::vec3> tCalcPos;
std::vector<glm::vec2> tCalcUV;
for (unsigned j = 0; j < 3; j++) {
tCalcPos.push_back(vertexData[faces[i].vertexData[j] - 1]);
tCalcUV.push_back(textureData[faces[i].textureData[j] - 1]);
}
glm::vec3 deltaPos = tCalcPos[1] - tCalcPos[0];
glm::vec3 deltaPos2 = tCalcPos[2] - tCalcPos[0];
glm::vec2 deltaUV = tCalcUV[1] - tCalcUV[0];
glm::vec2 deltaUV2 = tCalcUV[2] - tCalcUV[0];
float f = 1.0f / (deltaUV.x * deltaUV2.y - deltaUV.y * deltaUV2.x);
glm::vec3 tang = (deltaPos * deltaUV2.y - deltaPos2 * deltaUV.y) * f;
for (unsigned j = 0; j < 3; j++) {
tangs.push_back(tang);
}
}
for (unsigned i = 0; i < unPvertexData.size(); i++) {
master.push_back(unPvertexData[i]);
verts.push_back(unPvertexData[i]);
}
for (unsigned i = 0; i < unPtextureData.size(); i++) {
master.push_back(unPtextureData[i]);
texts.push_back(unPtextureData[i]);
}
for (unsigned i = 0; i < unPnormalData.size(); i++) {
master.push_back(unPnormalData[i]);
norms.push_back(unPnormalData[i]);
}
for (unsigned i = 0; i < tangs.size(); i++) {
master.push_back(tangs[i].x);
master.push_back(tangs[i].y);
master.push_back(tangs[i].z);
this->tangs.push_back(tangs[i].x);
this->tangs.push_back(tangs[i].y);
this->tangs.push_back(tangs[i].z);
}
glGenVertexArrays(1, &_VAO);
glGenBuffers(1, &_VBO);
//binding the vao
glBindVertexArray(_VAO);
//enable slots
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glBindBuffer(GL_ARRAY_BUFFER, _VBO);
//vertex
glBufferData(GL_ARRAY_BUFFER, master.size() * sizeof(float), &master[0], GL_STATIC_DRAW);
//verts
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
//texts
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(unPvertexData.size() * sizeof(float)));
//norms
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size()) * sizeof(float)));
//tangents
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size() + unPnormalData.size()) * sizeof(float)));
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size()) * sizeof(float)));
glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((unPtextureData.size() + unPvertexData.size() + unPnormalData.size()) * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
input.close();
return loaded = true;
}
void Mesh::loadFromData()
{
master.clear();
for (unsigned i = 0; i < verts.size(); i++)
master.push_back(verts[i]);
for (unsigned i = 0; i < texts.size(); i++)
master.push_back(texts[i]);
for (unsigned i = 0; i < norms.size(); i++)
master.push_back(norms[i]);
for (unsigned i = 0; i < tangs.size(); i++)
master.push_back(tangs[i]);
glGenVertexArrays(1, &_VAO);
glGenBuffers(1, &_VBO);
glBindVertexArray(_VAO);
//enable slots
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glBindBuffer(GL_ARRAY_BUFFER, _VBO);
//vertex
glBufferData(GL_ARRAY_BUFFER, master.size() * sizeof(float), &master[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float)));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float)));
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float)));
glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
loaded = true;
}
void Mesh::animationFunction(Mesh& other, bool shouldPlay)
{
glBindVertexArray(_VAO);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glBindBuffer(GL_ARRAY_BUFFER, _VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float)));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, other._VBO);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float)));
glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Mesh::resetVertAttribPointers()
{
glBindVertexArray(_VAO);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glBindBuffer(GL_ARRAY_BUFFER, _VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float)));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float)));
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float)));
glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Mesh::reload(const std::vector<float>& VERTS, const std::vector<float>& NORMS, const std::vector<float>& TANGS)
{
master.clear();
verts.clear();
norms.clear();
tangs.clear();
for (unsigned i = 0; i < VERTS.size(); i++) {
master.push_back(VERTS[i]);
verts.push_back(VERTS[i]);
}
for (unsigned i = 0; i < texts.size(); i++) {
master.push_back(texts[i]);
}
for (unsigned i = 0; i < NORMS.size(); i++) {
master.push_back(NORMS[i]);
norms.push_back(NORMS[i]);
}
for (unsigned i = 0; i < TANGS.size(); i++) {
master.push_back(TANGS[i]);
tangs.push_back(TANGS[i]);
}
glBindVertexArray(_VAO);
//enable slots
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, _VBO);
//vertex
glBufferSubData(GL_ARRAY_BUFFER, 0, master.size() * sizeof(float), &master[0]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(verts.size() * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size()) * sizeof(float)));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)((texts.size() + verts.size() + norms.size()) * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Mesh::unload()
{
//empty the buffers
glDeleteBuffers(1, &_VBO);
glDeleteVertexArrays(1, &_VAO);
_VBO = 0;
_VAO = 0;
//_numFaces = 0;//reset all numbers
//_numVerts = 0;
}
void Mesh::draw()
{
glBindVertexArray(_VAO);
glDrawArrays(GL_TRIANGLES, 0, _numVerts);
}
void Mesh::setDefaultPath(const std::string& directory) {
string dir = directory;
std::transform(dir.begin(), dir.end(), dir.begin(), ::tolower);
if (dir == "default")
_meshDirectory = "./Assets/Meshes/";
else
_meshDirectory = directory;
}
} | 13,358 | 5,973 |
// -*- coding: us-ascii-unix -*-
// Copyright 2013 Lukas Kemmer
//
// 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 FAINT_ID_TYPES_HH
#define FAINT_ID_TYPES_HH
namespace faint{
template<int group>
class FaintID{
public:
FaintID(){
static int max_id = 1007;
m_rawId = max_id++;
}
static FaintID Invalid(){
return FaintID(-1);
}
static FaintID DefaultID(){
return FaintID<group>(0);
}
bool operator==(const FaintID<group>& other) const{
return other.m_rawId == m_rawId;
}
bool operator!=(const FaintID<group>& other) const{
return !operator==(other);
}
bool operator<(const FaintID<group>& other) const{
return m_rawId < other.m_rawId;
}
bool operator>(const FaintID<group>& other) const{
return m_rawId > other.m_rawId;
}
int Raw() const{
return m_rawId;
}
private:
explicit FaintID(int id){
m_rawId = id;
}
int m_rawId;
};
using CanvasId = FaintID<107>;
using ObjectId = FaintID<108>;
using CommandId = FaintID<109>;
// 110 reserved
using FrameId = FaintID<111>;
} // namespace
#endif
| 1,586 | 576 |
// Copyright (C) 2014 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
#include "theia/util/hash.h"
#include "theia/util/map_util.h"
#include "theia/sfm/twoview_info.h"
#include "theia/sfm/types.h"
#include "theia/sfm/view_graph/view_graph.h"
namespace theia {
// This is needed for EXPECT_EQ(TwoViewInfo, TwoViewInfo);
bool operator==(const TwoViewInfo& lhs, const TwoViewInfo& rhs) {
return lhs.position_2 == rhs.position_2 &&
lhs.rotation_2 == rhs.rotation_2 &&
lhs.num_verified_matches == rhs.num_verified_matches;
}
TEST(ViewGraph, Constructor) {
ViewGraph view_graph;
EXPECT_EQ(view_graph.NumViews(), 0);
EXPECT_EQ(view_graph.NumEdges(), 0);
}
TEST(ViewGraph, RemoveView) {
ViewGraph graph;
const ViewId view_one = 0;
const ViewId view_two = 1;
const TwoViewInfo edge;
graph.AddEdge(view_one, view_two, edge);
EXPECT_TRUE(graph.HasView(view_one));
EXPECT_TRUE(graph.HasView(view_two));
EXPECT_EQ(graph.NumEdges(), 1);
graph.RemoveView(view_one);
EXPECT_TRUE(!graph.HasView(view_one));
EXPECT_EQ(graph.NumViews(), 1);
EXPECT_EQ(graph.NumEdges(), 0);
}
TEST(ViewGraph, AddEdge) {
TwoViewInfo info1;
info1.num_verified_matches = 1;
TwoViewInfo info2;
info2.num_verified_matches = 2;
ViewGraph graph;
graph.AddEdge(0, 1, info1);
graph.AddEdge(0, 2, info2);
EXPECT_EQ(graph.NumViews(), 3);
EXPECT_EQ(graph.NumEdges(), 2);
const std::vector<int> expected_ids = {0, 1, 2};
std::unordered_set<ViewId> view_ids = graph.ViewIds();
const auto* edge_0_1 = graph.GetEdge(0, 1);
const auto* edge_0_2 = graph.GetEdge(0, 2);
EXPECT_TRUE(edge_0_1 != nullptr);
EXPECT_EQ(*edge_0_1, info1);
EXPECT_TRUE(edge_0_2 != nullptr);
EXPECT_EQ(*edge_0_2, info2);
EXPECT_TRUE(graph.GetEdge(1, 2) == nullptr);
const auto* edge_1_0 = graph.GetEdge(1, 0);
const auto* edge_2_0 = graph.GetEdge(2, 0);
EXPECT_TRUE(edge_1_0 != nullptr);
EXPECT_EQ(*edge_1_0, info1);
EXPECT_EQ(*edge_2_0, info2);
EXPECT_TRUE(graph.GetEdge(2, 1) == nullptr);
const std::unordered_set<ViewId> edge_ids =
*graph.GetNeighborIdsForView(0);
EXPECT_TRUE(ContainsKey(edge_ids, 1));
EXPECT_TRUE(ContainsKey(edge_ids, 2));
TwoViewInfo info3;
info3.num_verified_matches = 3;
graph.AddEdge(1, 2, info3);
EXPECT_EQ(graph.NumViews(), 3);
EXPECT_EQ(graph.NumEdges(), 3);
EXPECT_TRUE(graph.GetEdge(1, 2) != nullptr);
EXPECT_EQ(*graph.GetEdge(1, 2), info3);
}
TEST(ViewGraph, RemoveEdge) {
TwoViewInfo info1;
info1.num_verified_matches = 1;
TwoViewInfo info2;
info2.num_verified_matches = 2;
ViewGraph graph;
graph.AddEdge(0, 1, info1);
graph.AddEdge(0, 2, info2);
EXPECT_TRUE(graph.GetEdge(0, 1) != nullptr);
EXPECT_TRUE(graph.GetEdge(0, 2) != nullptr);
EXPECT_EQ(graph.NumViews(), 3);
EXPECT_EQ(graph.NumEdges(), 2);
EXPECT_TRUE(graph.RemoveEdge(0, 2));
EXPECT_EQ(graph.NumEdges(), 1);
EXPECT_TRUE(graph.GetEdge(0, 2) == nullptr);
}
} // namespace theia
| 4,801 | 1,907 |
#include "StyleSwitcher.h"
uint64 Game_StyleSwitcher_counter = 0;
PrivateStart;
byte8 * StyleControllerProxy = 0;
byte8 * GunslingerGetStyleLevel = 0;
byte8 * VergilDynamicStyle = 0;
void UpdateStyle(byte8 * baseAddr, uint32 index)
{
auto actor = System_Actor_GetActorId(baseAddr);
auto & character = *(uint8 *)(baseAddr + 0x78);
auto & style = *(uint32 *)(baseAddr + 0x6338);
auto & level = *(uint32 *)(baseAddr + 0x6358);
auto & experience = *(float32 *)(baseAddr + 0x6364);
auto session = *(byte **)(appBaseAddr + 0xC90E30);
if (!session)
{
return;
}
auto sessionLevel = (uint32 *)(session + 0x11C);
auto sessionExperience = (float32 *)(session + 0x134);
if (!((character == CHAR_DANTE) || (character == CHAR_VERGIL)))
{
return;
}
if (character == CHAR_VERGIL)
{
switch (index)
{
case STYLE_SWORDMASTER:
case STYLE_GUNSLINGER:
case STYLE_ROYALGUARD:
index = STYLE_DARK_SLAYER;
break;
}
}
if (style == index)
{
if (Config.Game.StyleSwitcher.noDoubleTap)
{
return;
}
index = STYLE_QUICKSILVER;
}
if ((index == STYLE_QUICKSILVER) && (actor != ACTOR_ONE))
{
return;
}
if ((index == STYLE_DOPPELGANGER) && Config.System.Actor.forceSingleActor)
{
return;
}
// @Todo: Check if array for unlocked styles.
if (character == CHAR_DANTE)
{
if (index == STYLE_QUICKSILVER)
{
auto & unlock = *(bool *)(session + 0x5E);
if (!unlock)
{
return;
}
}
else if (index == STYLE_DOPPELGANGER)
{
auto & unlock = *(bool *)(session + 0x5F);
if (!unlock)
{
return;
}
}
}
if (actor == ACTOR_ONE)
{
sessionLevel [style] = level;
sessionExperience[style] = experience;
}
level = sessionLevel [index];
experience = sessionExperience[index];
style = index;
if ((index == STYLE_SWORDMASTER) || (index == STYLE_GUNSLINGER))
{
System_Weapon_Dante_UpdateExpertise(baseAddr);
}
UpdateActor2Start:
{
auto & baseAddr2 = System_Actor_actorBaseAddr[ACTOR_TWO];
if (!baseAddr2)
{
goto UpdateActor2End;
}
auto & character2 = *(uint8 *)(baseAddr2 + 0x78 );
auto & style2 = *(uint32 *)(baseAddr2 + 0x6338);
auto & isControlledByPlayer2 = *(bool *)(baseAddr2 + 0x6480);
if (Config.System.Actor.forceSingleActor)
{
goto UpdateActor2End;
}
if (actor != ACTOR_ONE)
{
goto UpdateActor2End;
}
if (character != character2)
{
goto UpdateActor2End;
}
if ((index == STYLE_QUICKSILVER) /*|| (index == STYLE_DOPPELGANGER)*/)
{
goto UpdateActor2End;
}
if (!isControlledByPlayer2)
{
style2 = index;
if ((index == STYLE_SWORDMASTER) || (index == STYLE_GUNSLINGER))
{
System_Weapon_Dante_UpdateExpertise(baseAddr2);
}
}
}
UpdateActor2End:
if (actor == ACTOR_ONE)
{
System_HUD_updateStyleIcon = true;
}
Game_StyleSwitcher_counter++;
}
PrivateEnd;
void Game_StyleSwitcher_Controller()
{
//uint8 actorCount = System_Actor_GetActorCount();
//if (actorCount < 1)
//{
// return;
//}
// @Todo: Change to bindings.
uint8 commandId[] =
{
CMD_MAP_SCREEN,
CMD_FILE_SCREEN,
CMD_ITEM_SCREEN,
CMD_EQUIP_SCREEN,
};
static bool execute[MAX_ACTOR][5] = {};
// @Fix: GetButtonState or loop is broken. Style is updated for other actors as well even if only actor one initiates the switch.
// @Todo: Create helper;
auto count = System_Actor_GetActorCount();
for (uint8 actor = 0; actor < count; actor++)
{
for (uint8 style = 0; style < 4; style++)
{
if (System_Input_GetButtonState(actor) & System_Input_GetBinding(commandId[style]))
{
if (execute[actor][style])
{
UpdateStyle(System_Actor_actorBaseAddr[actor], style);
execute[actor][style] = false;
}
}
else
{
execute[actor][style] = true;
}
}
if (Config.Game.Multiplayer.enable)
{
continue;
}
if ((System_Input_GetButtonState(actor) & System_Input_GetBinding(CMD_CHANGE_TARGET)) && (System_Input_GetButtonState(actor) & System_Input_GetBinding(CMD_DEFAULT_CAMERA)))
{
if (execute[actor][4])
{
UpdateStyle(System_Actor_actorBaseAddr[actor], STYLE_DOPPELGANGER);
execute[actor][4] = false;
}
}
else
{
execute[actor][4] = true;
}
}
}
void Game_StyleSwitcher_Init()
{
LogFunction();
{
byte8 sect0[] =
{
0x48, 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00, //mov rcx,[dmc3.exe+C90E30]
0x48, 0x85, 0xC9, //test rcx,rcx
0x74, 0x07, //je short
0x8B, 0x8B, 0x58, 0x63, 0x00, 0x00, //mov ecx,[rbx+00006358]
0xC3, //ret
0x8B, 0x89, 0x00, 0x00, 0x00, 0x00, //mov ecx,[rcx+00000000]
0xC3, //ret
};
FUNC func = CreateFunction(0, 0, false, true, sizeof(sect0));
memcpy(func.sect0, sect0, sizeof(sect0));
WriteAddress(func.sect0, (appBaseAddr + 0xC90E30), 7);
*(dword *)(func.sect0 + 0x15) = (0x11C + (STYLE_GUNSLINGER * 4));
GunslingerGetStyleLevel = func.addr;
}
{
byte8 sect0[] =
{
0x50, //push rax
0x56, //push rsi
0x48, 0x8B, 0x35, 0x00, 0x00, 0x00, 0x00, //mov rsi,[dmc3.exe+C90E30]
0x48, 0x85, 0xF6, //test rsi,rsi
0x74, 0x0C, //je short
0x8B, 0x86, 0xA4, 0x01, 0x00, 0x00, //mov eax,[rsi+000001A4]
0x89, 0x81, 0x38, 0x63, 0x00, 0x00, //mov [rcx+00006338],eax
0x5E, //pop rsi
0x58, //pop rax
};
FUNC func = CreateFunction(0, (appBaseAddr + 0x223D81), false, true, sizeof(sect0));
memcpy(func.sect0, sect0, sizeof(sect0));
WriteAddress((func.sect0 + 2), (appBaseAddr + 0xC90E30), 7);
VergilDynamicStyle = func.addr;
}
}
// @Todo: Update.
void Game_StyleSwitcher_Toggle(bool enable)
{
Log("%s %u", FUNC_NAME, enable);
if (enable)
{
Write<byte>((appBaseAddr + 0x1E8F98), 0xEB); // Bypass Character Check
//WriteJump((appBaseAddr + 0x23D4B2), StyleControllerProxy);
Write<byte>((appBaseAddr + 0x23B111), 0);
Write<byte>((appBaseAddr + 0x23B15E), 0);
Write<byte>((appBaseAddr + 0x23B1A2), 0);
Write<byte>((appBaseAddr + 0x23B1E6), 0);
// Gunslinger Fixes
WriteCall((appBaseAddr + 0x204E38), GunslingerGetStyleLevel, 1);
WriteCall((appBaseAddr + 0x205586), GunslingerGetStyleLevel, 1);
WriteCall((appBaseAddr + 0x208A90), GunslingerGetStyleLevel, 1);
WriteCall((appBaseAddr + 0x208F13), GunslingerGetStyleLevel, 1);
WriteAddress((appBaseAddr + 0x1E6AAD), (appBaseAddr + 0x1E6AB3), 6 ); // Allow Charged Shot
Write<byte>((appBaseAddr + 0x1E7F5F), 0xEB); // Allow Wild Stomp
WriteAddress((appBaseAddr + 0x21607C), (appBaseAddr + 0x216082), 6 ); // Allow Charging
// Force Style Updates
WriteAddress((appBaseAddr + 0x1F87BB), (appBaseAddr + 0x1F87DC), 6);
WriteAddress((appBaseAddr + 0x1F87C4), (appBaseAddr + 0x1F87DC), 6);
WriteAddress((appBaseAddr + 0x1F87CD), (appBaseAddr + 0x1F87DC), 6);
WriteAddress((appBaseAddr + 0x1F87D6), (appBaseAddr + 0x1F87DC), 6);
WriteAddress((appBaseAddr + 0x1F880B), (appBaseAddr + 0x1F8A00), 6);
WriteAddress((appBaseAddr + 0x1F8852), (appBaseAddr + 0x1F8A00), 6);
WriteAddress((appBaseAddr + 0x1F8862), (appBaseAddr + 0x1F8A00), 5);
WriteAddress((appBaseAddr + 0x1F886E), (appBaseAddr + 0x1F8A00), 6);
WriteAddress((appBaseAddr + 0x1F89E1), (appBaseAddr + 0x1F8A00), 6);
WriteAddress((appBaseAddr + 0x1F89FB), (appBaseAddr + 0x1F8A00), 5);
WriteAddress((appBaseAddr + 0x1F8A07), (appBaseAddr + 0x1F8AAC), 6);
WriteAddress((appBaseAddr + 0x1F8A7D), (appBaseAddr + 0x1F8AAC), 2);
WriteAddress((appBaseAddr + 0x1F8AAA), (appBaseAddr + 0x1F8AAC), 2);
WriteAddress((appBaseAddr + 0x1F8AC4), (appBaseAddr + 0x1F8AC6), 2);
// Vergil Fixes
WriteJump((appBaseAddr + 0x223D77), VergilDynamicStyle, 5); // Force dynamic style
// @Audit: Should this go to Actor.cpp? Yup, Doppelganger fix.
vp_memset((appBaseAddr + 0x221E50), 0x90, 8); // Update Actor Vergil; Disable linked actor base address reset.
}
else
{
Write<byte>((appBaseAddr + 0x1E8F98), 0x74);
//WriteCall((appBaseAddr + 0x23D4B2), (appBaseAddr + 0x23B060));
Write<byte>((appBaseAddr + 0x23B111), 1);
Write<byte>((appBaseAddr + 0x23B15E), 1);
Write<byte>((appBaseAddr + 0x23B1A2), 1);
Write<byte>((appBaseAddr + 0x23B1E6), 1);
{
byte buffer[] =
{
0x8B, 0x8B, 0x58, 0x63, 0x00, 0x00, //mov ecx,[rbx+00006358]
};
vp_memcpy((appBaseAddr + 0x204E38), buffer, sizeof(buffer));
vp_memcpy((appBaseAddr + 0x205586), buffer, sizeof(buffer));
vp_memcpy((appBaseAddr + 0x208A90), buffer, sizeof(buffer));
vp_memcpy((appBaseAddr + 0x208F13), buffer, sizeof(buffer));
}
WriteAddress((appBaseAddr + 0x1E6AAD), (appBaseAddr + 0x1E64A9), 6);
Write<byte>((appBaseAddr + 0x1E7F5F), 0x74);
WriteAddress((appBaseAddr + 0x21607C), (appBaseAddr + 0x216572), 6);
WriteAddress((appBaseAddr + 0x1F87BB), (appBaseAddr + 0x1F8AC6), 6);
WriteAddress((appBaseAddr + 0x1F87C4), (appBaseAddr + 0x1F8AAC), 6);
WriteAddress((appBaseAddr + 0x1F87CD), (appBaseAddr + 0x1F8A00), 6);
WriteAddress((appBaseAddr + 0x1F87D6), (appBaseAddr + 0x1F8AF8), 6);
WriteAddress((appBaseAddr + 0x1F880B), (appBaseAddr + 0x1F8AF8), 6);
WriteAddress((appBaseAddr + 0x1F8852), (appBaseAddr + 0x1F8AF8), 6);
WriteAddress((appBaseAddr + 0x1F8862), (appBaseAddr + 0x1F8AF8), 5);
WriteAddress((appBaseAddr + 0x1F886E), (appBaseAddr + 0x1F8AF8), 6);
WriteAddress((appBaseAddr + 0x1F89E1), (appBaseAddr + 0x1F8AF8), 6);
WriteAddress((appBaseAddr + 0x1F89FB), (appBaseAddr + 0x1F8AF8), 5);
WriteAddress((appBaseAddr + 0x1F8A07), (appBaseAddr + 0x1F8AF8), 6);
WriteAddress((appBaseAddr + 0x1F8A7D), (appBaseAddr + 0x1F8AF8), 2);
WriteAddress((appBaseAddr + 0x1F8AAA), (appBaseAddr + 0x1F8AF8), 2);
WriteAddress((appBaseAddr + 0x1F8AC4), (appBaseAddr + 0x1F8AF8), 2);
{
byte buffer[] =
{
0xC7, 0x81, 0x38, 0x63, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, //mov [rcx+00006338],00000002
};
vp_memcpy((appBaseAddr + 0x223D77), buffer, sizeof(buffer));
}
{
byte buffer[] =
{
0x4D, 0x89, 0xB4, 0x24, 0x78, 0x64, 0x00, 0x00, //mov [r12+00006478],r14
};
vp_memcpy((appBaseAddr + 0x221E50), buffer, sizeof(buffer));
}
}
}
| 10,370 | 5,290 |
#include "/Users/duc/github/ContestNeko/CodeForces/TaskD.cpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cctype>
#include <ctime>
namespace jhelper {
struct Test {
std::string input;
std::string output;
bool active;
bool has_output;
};
bool check(std::string expected, std::string actual) {
while(!expected.empty() && isspace(*--expected.end()))
expected.erase(--expected.end());
while(!actual.empty() && isspace(*--actual.end()))
actual.erase(--actual.end());
return expected == actual;
}
} // namespace jhelper
int main() {
std::vector<jhelper::Test> tests = {
{"5\n11 2 3 5 7\n4\n11 7 3 7\n", "3\n", true, true},{"2\n1 2\n1\n100\n", "-1\n", true, true},{"3\n1 2 3\n3\n1 2 3\n", "3\n", true, true},{"5\n1 2 3 4 5\n3 \n5 7 3", "", true, true},
};
bool allOK = true;
int testID = 0;
std::cout << std::fixed;
double maxTime = 0.0;
for(const jhelper::Test& test: tests ) {
std::cout << "Test #" << ++testID << std::endl;
std::cout << "Input: \n" << test.input << std::endl;
if (test.has_output) {
std::cout << "Expected output: \n" << test.output << std::endl;
}
else {
std::cout << "Expected output: \n" << "N/A" << std::endl;
}
if (test.active) {
std::stringstream in(test.input);
std::ostringstream out;
std::clock_t start = std::clock();
TaskD solver;
solver.solve(in, out);
std::clock_t finish = std::clock();
double currentTime = double(finish - start) / CLOCKS_PER_SEC;
maxTime = std::max(currentTime, maxTime);
std::cout << "Actual output: \n" << out.str() << std::endl;
if (test.has_output) {
bool result = jhelper::check(test.output, out.str());
allOK = allOK && result;
std::cout << "Result: " << (result ? "OK" : "Wrong answer") << std::endl;
}
std::cout << "Time: " << currentTime << std::endl;
}
else {
std::cout << "SKIPPED\n";
}
std::cout << std::endl;
}
if(allOK) {
std::cout << "All OK" << std::endl;
}
else {
std::cout << "Some cases failed" << std::endl;
}
std::cout << "Maximal time: " << maxTime << "s." << std::endl;
return 0;
} | 2,451 | 861 |
/* The copyright in this software is being made available under the BSD
* Licence, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such
* rights are granted under this licence.
*
* Copyright (c) 2017-2018, ISO/IEC
* 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 ISO/IEC 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 "TMC3.h"
#include <memory>
#include "PCCTMC3Encoder.h"
#include "PCCTMC3Decoder.h"
#include "constants.h"
#include "program_options_lite.h"
#include "io_tlv.h"
#include "version.h"
using namespace std;
using namespace pcc;
//============================================================================
struct Parameters {
bool isDecoder;
// command line parsing should adjust dist2 values according to PQS
bool positionQuantizationScaleAdjustsDist2;
// output mode for ply writing (binary or ascii)
bool outputBinaryPly;
// when true, configure the encoder as if no attributes are specified
bool disableAttributeCoding;
std::string uncompressedDataPath;
std::string compressedStreamPath;
std::string reconstructedDataPath;
// Filename for saving pre inverse scaled point cloud.
std::string preInvScalePath;
pcc::EncoderParams encoder;
pcc::DecoderParams decoder;
// todo(df): this should be per-attribute
ColorTransform colorTransform;
// todo(df): this should be per-attribute
int reflectanceScale;
};
//============================================================================
int
main(int argc, char* argv[])
{
cout << "MPEG PCC tmc3 version " << ::pcc::version << endl;
Parameters params;
if (!ParseParameters(argc, argv, params)) {
return -1;
}
// Timers to count elapsed wall/user time
pcc::chrono::Stopwatch<std::chrono::steady_clock> clock_wall;
pcc::chrono::Stopwatch<pcc::chrono::utime_inc_children_clock> clock_user;
clock_wall.start();
int ret = 0;
if (params.isDecoder) {
ret = Decompress(params, clock_user);
} else {
ret = Compress(params, clock_user);
}
clock_wall.stop();
using namespace std::chrono;
auto total_wall = duration_cast<milliseconds>(clock_wall.count()).count();
auto total_user = duration_cast<milliseconds>(clock_user.count()).count();
std::cout << "Processing time (wall): " << total_wall / 1000.0 << " s\n";
std::cout << "Processing time (user): " << total_user / 1000.0 << " s\n";
return ret;
}
//---------------------------------------------------------------------------
// :: Command line / config parsing helpers
template<typename T>
static std::istream&
readUInt(std::istream& in, T& val)
{
unsigned int tmp;
in >> tmp;
val = T(tmp);
return in;
}
static std::istream&
operator>>(std::istream& in, ColorTransform& val)
{
return readUInt(in, val);
}
namespace pcc {
static std::istream&
operator>>(std::istream& in, AttributeEncoding& val)
{
return readUInt(in, val);
}
} // namespace pcc
namespace pcc {
static std::istream&
operator>>(std::istream& in, PartitionMethod& val)
{
return readUInt(in, val);
}
} // namespace pcc
namespace pcc {
static std::ostream&
operator<<(std::ostream& out, const AttributeEncoding& val)
{
switch (val) {
case AttributeEncoding::kPredictingTransform: out << "0 (Pred)"; break;
case AttributeEncoding::kRAHTransform: out << "1 (RAHT)"; break;
case AttributeEncoding::kLiftingTransform: out << "2 (Lift)"; break;
}
return out;
}
} // namespace pcc
namespace pcc {
static std::ostream&
operator<<(std::ostream& out, const PartitionMethod& val)
{
switch (val) {
case PartitionMethod::kNone: out << "0 (None)"; break;
case PartitionMethod::kUniformGeom: out << "0 (UniformGeom)"; break;
case PartitionMethod::kOctreeUniform: out << "0 (UniformOctree)"; break;
default: out << int(val) << " (Unknown)"; break;
}
return out;
}
} // namespace pcc
namespace df {
namespace program_options_lite {
template<typename T>
struct option_detail<pcc::PCCVector3<T>> {
static constexpr bool is_container = true;
static constexpr bool is_fixed_size = true;
typedef T* output_iterator;
static void clear(pcc::PCCVector3<T>& container){};
static output_iterator make_output_iterator(pcc::PCCVector3<T>& container)
{
return &container[0];
}
};
} // namespace program_options_lite
} // namespace df
//---------------------------------------------------------------------------
// :: Command line / config parsing
bool
ParseParameters(int argc, char* argv[], Parameters& params)
{
namespace po = df::program_options_lite;
struct {
AttributeDescription desc;
AttributeParameterSet aps;
} params_attr;
bool print_help = false;
// a helper to set the attribute
std::function<po::OptionFunc::Func> attribute_setter =
[&](po::Options&, const std::string& name, po::ErrorReporter) {
// copy the current state of parsed attribute parameters
//
// NB: this does not cause the default values of attr to be restored
// for the next attribute block. A side-effect of this is that the
// following is allowed leading to attribute foo having both X=1 and
// Y=2:
// "--attr.X=1 --attribute foo --attr.Y=2 --attribute foo"
//
// NB: insert returns any existing element
const auto& it = params.encoder.attributeIdxMap.insert(
{name, int(params.encoder.attributeIdxMap.size())});
if (it.second) {
params.encoder.sps.attributeSets.push_back(params_attr.desc);
params.encoder.aps.push_back(params_attr.aps);
return;
}
// update existing entry
params.encoder.sps.attributeSets[it.first->second] = params_attr.desc;
params.encoder.aps[it.first->second] = params_attr.aps;
};
/* clang-format off */
// The definition of the program/config options, along with default values.
//
// NB: when updating the following tables:
// (a) please keep to 80-columns for easier reading at a glance,
// (b) do not vertically align values -- it breaks quickly
//
po::Options opts;
opts.addOptions()
("help", print_help, false, "this help text")
("config,c", po::parseConfigFile, "configuration file name")
(po::Section("General"))
("mode", params.isDecoder, false,
"The encoding/decoding mode:\n"
" 0: encode\n"
" 1: decode")
// i/o parameters
("reconstructedDataPath",
params.reconstructedDataPath, {},
"The ouput reconstructed pointcloud file path (decoder only)")
("uncompressedDataPath",
params.uncompressedDataPath, {},
"The input pointcloud file path")
("compressedStreamPath",
params.compressedStreamPath, {},
"The compressed bitstream path (encoder=output, decoder=input)")
("postRecolorPath",
params.encoder.postRecolorPath, {},
"Recolored pointcloud file path (encoder only)")
("preInvScalePath",
params.preInvScalePath, {},
"Pre inverse scaled pointcloud file path (decoder only)")
("outputBinaryPly",
params.outputBinaryPly, false,
"Output ply files using binary (or otherwise ascii) format")
// general
// todo(df): this should be per-attribute
("colorTransform",
params.colorTransform, COLOR_TRANSFORM_RGB_TO_YCBCR,
"The colour transform to be applied:\n"
" 0: none\n"
" 1: RGB to YCbCr (Rec.709)")
// todo(df): this should be per-attribute
("hack.reflectanceScale",
params.reflectanceScale, 1,
"scale factor to be applied to reflectance "
"pre encoding / post reconstruction")
// NB: if adding decoder options, uncomment the Decoder section marker
// (po::Section("Decoder"))
(po::Section("Encoder"))
("seq_bounding_box_xyz0",
params.encoder.sps.seq_bounding_box_xyz0, {0},
"seq_bounding_box_xyz0. NB: seq_bounding_box_whd must be set for this "
"parameter to have an effect")
("seq_bounding_box_whd",
params.encoder.sps.seq_bounding_box_whd, {0},
"seq_bounding_box_whd")
("positionQuantizationScale",
params.encoder.sps.seq_source_geom_scale_factor, 1.f,
"Scale factor to be applied to point positions during quantization process")
("positionQuantizationScaleAdjustsDist2",
params.positionQuantizationScaleAdjustsDist2, false,
"Scale dist2 values by squared positionQuantizationScale")
("mergeDuplicatedPoints",
params.encoder.gps.geom_unique_points_flag, true,
"Enables removal of duplicated points")
("partitionMethod",
params.encoder.partitionMethod, PartitionMethod::kNone,
"Method used to partition input point cloud into slices/tiles:\n"
" 0: none\n"
" 1: none (deprecated)\n"
" 2: n Uniform-Geometry partition bins along the longest edge\n"
" 3: Uniform Geometry partition at n octree depth")
("partitionNumUniformGeom",
params.encoder.partitionNumUniformGeom, 0,
"Number of bins for partitionMethod=2:\n"
" 0: slice partition with adaptive-defined bins\n"
" >=1: slice partition with user-defined bins\n")
("partitionOctreeDepth",
params.encoder.partitionOctreeDepth, 2,
"Depth of octree partition for partitionMethod=3")
("disableAttributeCoding",
params.disableAttributeCoding, false,
"Ignore attribute coding configuration")
(po::Section("Geometry"))
// tools
("bitwiseOccupancyCoding",
params.encoder.gps.bitwise_occupancy_coding_flag, true,
"Selects between bitwise and bytewise occupancy coding:\n"
" 0: bytewise\n"
" 1: bitwise")
("neighbourContextRestriction",
params.encoder.gps.neighbour_context_restriction_flag, false,
"Limit geometry octree occupancy contextualisation to sibling nodes")
("neighbourAvailBoundaryLog2",
params.encoder.gps.neighbour_avail_boundary_log2, 0,
"Defines the avaliability volume for neighbour occupancy lookups."
" 0: unconstrained")
("inferredDirectCodingMode",
params.encoder.gps.inferred_direct_coding_mode_enabled_flag, true,
"Permits early termination of the geometry octree for isolated points")
("intra_pred_max_node_size_log2",
params.encoder.gps.intra_pred_max_node_size_log2, 0,
"octree nodesizes eligible for occupancy intra prediction")
("ctxOccupancyReductionFactor",
params.encoder.gps.geom_occupancy_ctx_reduction_factor, 3,
"Adjusts the number of contexts used in occupancy coding")
("trisoup_node_size_log2",
params.encoder.gps.trisoup_node_size_log2, 0,
"Size of nodes for surface triangulation.\n"
" 0: disabled\n")
(po::Section("Attributes"))
// attribute processing
// NB: Attribute options are special in the way they are applied (see above)
("attribute",
attribute_setter,
"Encode the given attribute (NB, must appear after the"
"following attribute parameters)")
("bitdepth",
params_attr.desc.attr_bitdepth, 8,
"Attribute bitdepth")
("transformType",
params_attr.aps.attr_encoding, AttributeEncoding::kPredictingTransform,
"Coding method to use for attribute:\n"
" 0: Hierarchical neighbourhood prediction\n"
" 1: Region Adaptive Hierarchical Transform (RAHT)\n"
" 2: Hierarichical neighbourhood prediction as lifting transform")
("rahtLeafDecimationDepth",
params_attr.aps.raht_binary_level_threshold, 3,
"Sets coefficients to zero in the bottom n levels of RAHT tree. "
"Used for chroma-subsampling in attribute=color only.")
("rahtQuantizationStep",
params_attr.aps.quant_step_size_luma, 0,
"deprecated -- use quantizationStepsLuma")
("rahtDepth",
params_attr.aps.raht_depth, 21,
"Number of bits for morton representation of an RAHT co-ordinate"
"component")
("numberOfNearestNeighborsInPrediction",
params_attr.aps.num_pred_nearest_neighbours, 3,
"Attribute's maximum number of nearest neighbors to be used for prediction")
("adaptivePredictionThreshold",
params_attr.aps.adaptive_prediction_threshold, -1,
"Neighbouring attribute value difference that enables choice of "
"single|multi predictors. Applies to transformType=2 only.\n"
" -1: auto = 2**(bitdepth-2)")
("attributeSearchRange",
params_attr.aps.search_range, 128,
"Range for nearest neighbor search")
("lodBinaryTree",
params_attr.aps.lod_binary_tree_enabled_flag, false,
"Controls LoD generation method:\n"
" 0: distance based subsampling\n"
" 1: binary tree")
("max_num_direct_predictors",
params_attr.aps.max_num_direct_predictors, 3,
"Maximum number of nearest neighbour candidates used in direct"
"attribute prediction")
("levelOfDetailCount",
params_attr.aps.num_detail_levels, 1,
"Attribute's number of levels of detail")
("quantizationStepLuma",
params_attr.aps.quant_step_size_luma, 0,
"Attribute's luma quantization step size")
("quantizationStepChroma",
params_attr.aps.quant_step_size_chroma, 0,
"Attribute's chroma quantization step size")
("dist2",
params_attr.aps.dist2, {},
"Attribute's list of squared distances, or initial value for automatic"
"derivation")
;
/* clang-format on */
po::setDefaults(opts);
po::ErrorReporter err;
const list<const char*>& argv_unhandled =
po::scanArgv(opts, argc, (const char**)argv, err);
for (const auto arg : argv_unhandled) {
err.warn() << "Unhandled argument ignored: " << arg << "\n";
}
if (argc == 1 || print_help) {
po::doHelp(std::cout, opts, 78);
return false;
}
// Certain coding modes are not available when trisoup is enabled.
// Disable them, and warn if set (they may be set as defaults).
if (params.encoder.gps.trisoup_node_size_log2 > 0) {
if (!params.encoder.gps.geom_unique_points_flag)
err.warn() << "TriSoup geometry does not preserve duplicated points\n";
if (params.encoder.gps.inferred_direct_coding_mode_enabled_flag)
err.warn() << "TriSoup geometry is incompatable with IDCM\n";
params.encoder.gps.geom_unique_points_flag = true;
params.encoder.gps.inferred_direct_coding_mode_enabled_flag = false;
}
// support disabling attribute coding (simplifies configuration)
if (params.disableAttributeCoding) {
params.encoder.attributeIdxMap.clear();
params.encoder.sps.attributeSets.clear();
params.encoder.aps.clear();
}
// fixup any per-attribute settings
for (const auto& it : params.encoder.attributeIdxMap) {
auto& attr_sps = params.encoder.sps.attributeSets[it.second];
auto& attr_aps = params.encoder.aps[it.second];
// Avoid wasting bits signalling chroma quant step size for reflectance
if (it.first == "reflectance") {
attr_aps.quant_step_size_chroma = 0;
}
bool isLifting =
attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform
|| attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform;
// derive the dist2 values based on an initial value
if (isLifting) {
if (attr_aps.dist2.size() > attr_aps.num_detail_levels) {
attr_aps.dist2.resize(attr_aps.num_detail_levels);
} else if (
attr_aps.dist2.size() < attr_aps.num_detail_levels
&& !attr_aps.dist2.empty()) {
if (attr_aps.dist2.size() < attr_aps.num_detail_levels) {
attr_aps.dist2.resize(attr_aps.num_detail_levels);
const double distRatio = 4.0;
uint64_t d2 = attr_aps.dist2[0];
for (int i = 0; i < attr_aps.num_detail_levels; ++i) {
attr_aps.dist2[i] = d2;
d2 = uint64_t(std::round(distRatio * d2));
}
}
}
}
// In order to simplify specification of dist2 values, which are
// depending on the scale of the coded point cloud, the following
// adjust the dist2 values according to PQS. The user need only
// specify the unquantised PQS value.
if (params.positionQuantizationScaleAdjustsDist2) {
double pqs = params.encoder.sps.seq_source_geom_scale_factor;
double pqs2 = pqs * pqs;
for (auto& dist2 : attr_aps.dist2)
dist2 = int64_t(std::round(pqs2 * dist2));
}
// Set default threshold based on bitdepth
if (attr_aps.adaptive_prediction_threshold == -1) {
attr_aps.adaptive_prediction_threshold = 1
<< (attr_sps.attr_bitdepth - 2);
}
if (attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform) {
attr_aps.adaptive_prediction_threshold = 0;
}
// For RAHT, ensure that the unused lod count = 0 (prevents mishaps)
if (attr_aps.attr_encoding == AttributeEncoding::kRAHTransform) {
attr_aps.num_detail_levels = 0;
attr_aps.adaptive_prediction_threshold = 0;
// todo(df): suggest chroma quant_step_size for raht
attr_aps.quant_step_size_chroma = 0;
}
}
// sanity checks
if (params.encoder.gps.intra_pred_max_node_size_log2)
if (!params.encoder.gps.neighbour_avail_boundary_log2)
err.error() << "Geometry intra prediction requires finite"
"neighbour_avail_boundary_log2\n";
for (const auto& it : params.encoder.attributeIdxMap) {
const auto& attr_sps = params.encoder.sps.attributeSets[it.second];
const auto& attr_aps = params.encoder.aps[it.second];
bool isLifting =
attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform
|| attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform;
if (it.first == "color") {
// todo(??): permit relaxing of the following constraint
if (attr_sps.attr_bitdepth > 8)
err.error() << it.first << ".bitdepth must be less than 9\n";
}
if (it.first == "reflectance") {
if (attr_sps.attr_bitdepth > 16)
err.error() << it.first << ".bitdepth must be less than 17\n";
}
if (isLifting) {
int lod = attr_aps.num_detail_levels;
if (lod > 255 || lod < 0) {
err.error() << it.first
<< ".levelOfDetailCount must be in the range [0,255]\n";
}
if (attr_aps.dist2.size() != lod) {
err.error() << it.first << ".dist2 does not have " << lod
<< " entries\n";
}
if (attr_aps.adaptive_prediction_threshold < 0) {
err.error() << it.first
<< ".adaptivePredictionThreshold must be positive\n";
}
if (
attr_aps.num_pred_nearest_neighbours
> kAttributePredictionMaxNeighbourCount) {
err.error() << it.first
<< ".numberOfNearestNeighborsInPrediction must be <= "
<< kAttributePredictionMaxNeighbourCount << "\n";
}
}
}
// check required arguments are specified
if (!params.isDecoder && params.uncompressedDataPath.empty())
err.error() << "uncompressedDataPath not set\n";
if (params.isDecoder && params.reconstructedDataPath.empty())
err.error() << "reconstructedDataPath not set\n";
if (params.compressedStreamPath.empty())
err.error() << "compressedStreamPath not set\n";
// report the current configuration (only in the absence of errors so
// that errors/warnings are more obvious and in the same place).
if (err.is_errored)
return false;
// Dump the complete derived configuration
cout << "+ Effective configuration parameters\n";
po::dumpCfg(cout, opts, "General", 4);
if (params.isDecoder) {
po::dumpCfg(cout, opts, "Decoder", 4);
} else {
po::dumpCfg(cout, opts, "Encoder", 4);
po::dumpCfg(cout, opts, "Geometry", 4);
for (const auto& it : params.encoder.attributeIdxMap) {
// NB: when dumping the config, opts references params_attr
params_attr.desc = params.encoder.sps.attributeSets[it.second];
params_attr.aps = params.encoder.aps[it.second];
cout << " " << it.first << "\n";
po::dumpCfg(cout, opts, "Attributes", 8);
}
}
cout << endl;
return true;
}
int
Compress(Parameters& params, Stopwatch& clock)
{
PCCPointSet3 pointCloud;
if (
!pointCloud.read(params.uncompressedDataPath)
|| pointCloud.getPointCount() == 0) {
cout << "Error: can't open input file!" << endl;
return -1;
}
// Sanitise the input point cloud
// todo(df): remove the following with generic handling of properties
bool codeColour = params.encoder.attributeIdxMap.count("color");
if (!codeColour)
pointCloud.removeColors();
assert(codeColour == pointCloud.hasColors());
bool codeReflectance = params.encoder.attributeIdxMap.count("reflectance");
if (!codeReflectance)
pointCloud.removeReflectances();
assert(codeReflectance == pointCloud.hasReflectances());
ofstream fout(params.compressedStreamPath, ios::binary);
if (!fout.is_open()) {
return -1;
}
clock.start();
if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
pointCloud.convertRGBToYUV();
}
if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) {
const auto pointCount = pointCloud.getPointCount();
for (size_t i = 0; i < pointCount; ++i) {
int val = pointCloud.getReflectance(i) / params.reflectanceScale;
pointCloud.setReflectance(i, val);
}
}
PCCTMC3Encoder3 encoder;
// The reconstructed point cloud
std::unique_ptr<PCCPointSet3> reconPointCloud;
if (!params.reconstructedDataPath.empty()) {
reconPointCloud.reset(new PCCPointSet3);
}
int ret = encoder.compress(
pointCloud, ¶ms.encoder,
[&](const PayloadBuffer& buf) { writeTlv(buf, fout); },
reconPointCloud.get());
if (ret) {
cout << "Error: can't compress point cloud!" << endl;
return -1;
}
std::cout << "Total bitstream size " << fout.tellp() << " B" << std::endl;
fout.close();
clock.stop();
if (!params.reconstructedDataPath.empty()) {
if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
reconPointCloud->convertYUVToRGB();
}
if (params.reflectanceScale > 1 && reconPointCloud->hasReflectances()) {
const auto pointCount = reconPointCloud->getPointCount();
for (size_t i = 0; i < pointCount; ++i) {
int val = reconPointCloud->getReflectance(i) * params.reflectanceScale;
reconPointCloud->setReflectance(i, val);
}
}
reconPointCloud->write(
params.reconstructedDataPath, !params.outputBinaryPly);
}
return 0;
}
int
Decompress(Parameters& params, Stopwatch& clock)
{
ifstream fin(params.compressedStreamPath, ios::binary);
if (!fin.is_open()) {
return -1;
}
clock.start();
PayloadBuffer buf;
PCCTMC3Decoder3 decoder;
while (true) {
PayloadBuffer* buf_ptr = &buf;
readTlv(fin, &buf);
// at end of file (or other error), flush decoder
if (!fin)
buf_ptr = nullptr;
int ret = decoder.decompress(
params.decoder, buf_ptr, [&](const PCCPointSet3& decodedPointCloud) {
PCCPointSet3 pointCloud(decodedPointCloud);
if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) {
pointCloud.convertYUVToRGB();
}
if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) {
const auto pointCount = pointCloud.getPointCount();
for (size_t i = 0; i < pointCount; ++i) {
int val = pointCloud.getReflectance(i) * params.reflectanceScale;
pointCloud.setReflectance(i, val);
}
}
// Dump the decoded colour using the pre inverse scaled geometry
if (!params.preInvScalePath.empty()) {
pointCloud.write(params.preInvScalePath, !params.outputBinaryPly);
}
decoder.inverseQuantization(pointCloud);
clock.stop();
if (!pointCloud.write(
params.reconstructedDataPath, !params.outputBinaryPly)) {
cout << "Error: can't open output file!" << endl;
}
clock.start();
});
if (ret) {
cout << "Error: can't decompress point cloud!" << endl;
return -1;
}
if (!buf_ptr)
break;
}
fin.clear();
fin.seekg(0, ios_base::end);
std::cout << "Total bitstream size " << fin.tellg() << " B" << std::endl;
clock.stop();
return 0;
}
| 25,405 | 8,433 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill/core/browser/ui/label_formatter_utils.h"
#include <algorithm>
#include <iterator>
#include <memory>
#include "base/bind.h"
#include "base/callback.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/autofill_data_util.h"
#include "components/autofill/core/browser/geo/address_i18n.h"
#include "components/autofill/core/browser/geo/phone_number_i18n.h"
#include "components/autofill/core/browser/validation.h"
#include "components/grit/components_scaled_resources.h"
#include "components/strings/grit/components_strings.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h"
#include "ui/base/l10n/l10n_util.h"
namespace autofill {
using data_util::ContainsAddress;
using data_util::ContainsEmail;
using data_util::ContainsName;
using data_util::ContainsPhone;
namespace {
// Returns true if all |profiles| have the same value for the data retrieved by
// |get_data|.
bool HaveSameData(
const std::vector<AutofillProfile*>& profiles,
const std::string& app_locale,
base::RepeatingCallback<base::string16(const AutofillProfile&,
const std::string&)> get_data,
base::RepeatingCallback<bool(const base::string16& str1,
const base::string16& str2)> matches) {
if (profiles.size() <= 1) {
return true;
}
const base::string16 first_profile_data =
get_data.Run(*profiles[0], app_locale);
for (size_t i = 1; i < profiles.size(); ++i) {
const base::string16 current_profile_data =
get_data.Run(*profiles[i], app_locale);
if (!matches.Run(first_profile_data, current_profile_data)) {
return false;
}
}
return true;
}
// Used to avoid having the same lambda in HaveSameEmailAddresses,
// HaveSameFirstNames, HaveSameStreetAddresses.
bool Equals(const base::string16& str1, const base::string16& str2) {
return str1 == str2;
}
} // namespace
void AddLabelPartIfNotEmpty(const base::string16& part,
std::vector<base::string16>* parts) {
if (!part.empty()) {
parts->push_back(part);
}
}
base::string16 ConstructLabelLine(const std::vector<base::string16>& parts) {
return base::JoinString(parts, l10n_util::GetStringUTF16(
IDS_AUTOFILL_SUGGESTION_LABEL_SEPARATOR));
}
base::string16 ConstructMobileLabelLine(
const std::vector<base::string16>& parts) {
return base::JoinString(
parts, l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESS_SUMMARY_SEPARATOR));
}
bool IsNonStreetAddressPart(ServerFieldType type) {
switch (type) {
case ADDRESS_HOME_CITY:
case ADDRESS_BILLING_CITY:
case ADDRESS_HOME_ZIP:
case ADDRESS_BILLING_ZIP:
case ADDRESS_HOME_STATE:
case ADDRESS_BILLING_STATE:
case ADDRESS_HOME_COUNTRY:
case ADDRESS_BILLING_COUNTRY:
case ADDRESS_HOME_SORTING_CODE:
case ADDRESS_BILLING_SORTING_CODE:
case ADDRESS_HOME_DEPENDENT_LOCALITY:
case ADDRESS_BILLING_DEPENDENT_LOCALITY:
return true;
default:
return false;
}
}
bool IsStreetAddressPart(ServerFieldType type) {
switch (type) {
case ADDRESS_HOME_LINE1:
case ADDRESS_HOME_LINE2:
case ADDRESS_HOME_APT_NUM:
case ADDRESS_BILLING_LINE1:
case ADDRESS_BILLING_LINE2:
case ADDRESS_BILLING_APT_NUM:
case ADDRESS_HOME_STREET_ADDRESS:
case ADDRESS_BILLING_STREET_ADDRESS:
case ADDRESS_HOME_LINE3:
case ADDRESS_BILLING_LINE3:
return true;
default:
return false;
}
}
bool HasNonStreetAddress(const std::vector<ServerFieldType>& types) {
return base::ranges::any_of(types, IsNonStreetAddressPart);
}
bool HasStreetAddress(const std::vector<ServerFieldType>& types) {
return base::ranges::any_of(types, IsStreetAddressPart);
}
std::vector<ServerFieldType> ExtractSpecifiedAddressFieldTypes(
bool extract_street_address_types,
const std::vector<ServerFieldType>& types) {
auto should_be_extracted =
[&extract_street_address_types](ServerFieldType type) -> bool {
return AutofillType(AutofillType(type).GetStorableType()).group() ==
FieldTypeGroup::kAddressHome &&
(extract_street_address_types ? IsStreetAddressPart(type)
: !IsStreetAddressPart(type));
};
std::vector<ServerFieldType> extracted_address_types;
std::copy_if(types.begin(), types.end(),
std::back_inserter(extracted_address_types),
should_be_extracted);
return extracted_address_types;
}
std::vector<ServerFieldType> TypesWithoutFocusedField(
const std::vector<ServerFieldType>& types,
ServerFieldType field_type_to_remove) {
std::vector<ServerFieldType> types_without_field;
std::copy_if(types.begin(), types.end(),
std::back_inserter(types_without_field),
[&field_type_to_remove](ServerFieldType type) -> bool {
return type != field_type_to_remove;
});
return types_without_field;
}
AutofillProfile MakeTrimmedProfile(const AutofillProfile& profile,
const std::string& app_locale,
const std::vector<ServerFieldType>& types) {
AutofillProfile trimmed_profile(profile.guid(), profile.origin());
trimmed_profile.set_language_code(profile.language_code());
const AutofillType country_code_type(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE);
const base::string16 country_code =
profile.GetInfo(country_code_type, app_locale);
trimmed_profile.SetInfo(country_code_type, country_code, app_locale);
for (const ServerFieldType& type : types) {
trimmed_profile.SetInfo(type, profile.GetInfo(type, app_locale),
app_locale);
}
return trimmed_profile;
}
base::string16 GetLabelForFocusedAddress(
ServerFieldType focused_field_type,
bool form_has_street_address,
const AutofillProfile& profile,
const std::string& app_locale,
const std::vector<ServerFieldType>& types) {
return GetLabelAddress(
form_has_street_address && !IsStreetAddressPart(focused_field_type),
profile, app_locale, types);
}
base::string16 GetLabelAddress(bool use_street_address,
const AutofillProfile& profile,
const std::string& app_locale,
const std::vector<ServerFieldType>& types) {
return use_street_address
? GetLabelStreetAddress(
ExtractSpecifiedAddressFieldTypes(use_street_address, types),
profile, app_locale)
: GetLabelNationalAddress(
ExtractSpecifiedAddressFieldTypes(use_street_address, types),
profile, app_locale);
}
base::string16 GetLabelNationalAddress(
const std::vector<ServerFieldType>& types,
const AutofillProfile& profile,
const std::string& app_locale) {
std::unique_ptr<::i18n::addressinput::AddressData> address_data =
i18n::CreateAddressDataFromAutofillProfile(
MakeTrimmedProfile(profile, app_locale, types), app_locale);
std::string address_line;
::i18n::addressinput::GetFormattedNationalAddressLine(*address_data,
&address_line);
return base::UTF8ToUTF16(address_line);
}
base::string16 GetLabelStreetAddress(const std::vector<ServerFieldType>& types,
const AutofillProfile& profile,
const std::string& app_locale) {
std::unique_ptr<::i18n::addressinput::AddressData> address_data =
i18n::CreateAddressDataFromAutofillProfile(
MakeTrimmedProfile(profile, app_locale, types), app_locale);
std::string address_line;
::i18n::addressinput::GetStreetAddressLinesAsSingleLine(*address_data,
&address_line);
return base::UTF8ToUTF16(address_line);
}
base::string16 GetLabelForProfileOnFocusedNonStreetAddress(
bool form_has_street_address,
const AutofillProfile& profile,
const std::string& app_locale,
const std::vector<ServerFieldType>& types,
const base::string16& contact_info) {
std::vector<base::string16> label_parts;
AddLabelPartIfNotEmpty(
GetLabelAddress(form_has_street_address, profile, app_locale, types),
&label_parts);
AddLabelPartIfNotEmpty(contact_info, &label_parts);
return ConstructLabelLine(label_parts);
}
base::string16 GetLabelName(const std::vector<ServerFieldType>& types,
const AutofillProfile& profile,
const std::string& app_locale) {
bool has_first_name = false;
bool has_last_name = false;
bool has_full_name = false;
for (const ServerFieldType type : types) {
if (type == NAME_FULL) {
has_full_name = true;
break;
}
if (type == NAME_FIRST) {
has_first_name = true;
}
if (type == NAME_LAST) {
has_last_name = true;
}
}
if (has_full_name) {
return profile.GetInfo(AutofillType(NAME_FULL), app_locale);
}
if (has_first_name && has_last_name) {
std::vector<base::string16> name_parts;
AddLabelPartIfNotEmpty(GetLabelFirstName(profile, app_locale), &name_parts);
AddLabelPartIfNotEmpty(profile.GetInfo(AutofillType(NAME_LAST), app_locale),
&name_parts);
return base::JoinString(name_parts, base::ASCIIToUTF16(" "));
}
if (has_first_name) {
return GetLabelFirstName(profile, app_locale);
}
if (has_last_name) {
return profile.GetInfo(AutofillType(NAME_LAST), app_locale);
}
// The form contains neither a full name field nor a first name field,
// so choose some name field in the form and make it the label text.
for (const ServerFieldType type : types) {
if (AutofillType(AutofillType(type).GetStorableType()).group() ==
FieldTypeGroup::kName) {
return profile.GetInfo(AutofillType(type), app_locale);
}
}
return base::string16();
}
base::string16 GetLabelFirstName(const AutofillProfile& profile,
const std::string& app_locale) {
return profile.GetInfo(AutofillType(NAME_FIRST), app_locale);
}
base::string16 GetLabelEmail(const AutofillProfile& profile,
const std::string& app_locale) {
const base::string16 email =
profile.GetInfo(AutofillType(EMAIL_ADDRESS), app_locale);
return IsValidEmailAddress(email) ? email : base::string16();
}
base::string16 GetLabelPhone(const AutofillProfile& profile,
const std::string& app_locale) {
const std::string unformatted_phone = base::UTF16ToUTF8(
profile.GetInfo(AutofillType(PHONE_HOME_WHOLE_NUMBER), app_locale));
return unformatted_phone.empty()
? base::string16()
: base::UTF8ToUTF16(i18n::FormatPhoneNationallyForDisplay(
unformatted_phone,
data_util::GetCountryCodeWithFallback(profile, app_locale)));
}
bool HaveSameEmailAddresses(const std::vector<AutofillProfile*>& profiles,
const std::string& app_locale) {
return HaveSameData(profiles, app_locale, base::BindRepeating(&GetLabelEmail),
base::BindRepeating(base::BindRepeating(&Equals)));
}
bool HaveSameFirstNames(const std::vector<AutofillProfile*>& profiles,
const std::string& app_locale) {
return HaveSameData(profiles, app_locale,
base::BindRepeating(&GetLabelFirstName),
base::BindRepeating(base::BindRepeating(&Equals)));
}
bool HaveSameNonStreetAddresses(const std::vector<AutofillProfile*>& profiles,
const std::string& app_locale,
const std::vector<ServerFieldType>& types) {
// In general, comparing non street addresses with Equals, which uses ==, is
// not ideal since Düsseldorf and Dusseldorf will be considered distinct. It's
// okay to use it here because near-duplicate non street addresses like this
// are filtered out before a LabelFormatter is created.
return HaveSameData(profiles, app_locale,
base::BindRepeating(&GetLabelNationalAddress, types),
base::BindRepeating(&Equals));
}
bool HaveSamePhoneNumbers(const std::vector<AutofillProfile*>& profiles,
const std::string& app_locale) {
// Note that the same country code is used in all comparisons.
auto equals = [](const std::string& country_code,
const std::string& app_locale, const base::string16& phone1,
const base::string16& phone2) -> bool {
return (phone1.empty() && phone2.empty()) ||
i18n::PhoneNumbersMatch(phone1, phone2, country_code, app_locale);
};
return profiles.size() <= 1
? true
: HaveSameData(
profiles, app_locale, base::BindRepeating(&GetLabelPhone),
base::BindRepeating(equals,
base::UTF16ToASCII(profiles[0]->GetInfo(
ADDRESS_HOME_COUNTRY, app_locale)),
app_locale));
}
bool HaveSameStreetAddresses(const std::vector<AutofillProfile*>& profiles,
const std::string& app_locale,
const std::vector<ServerFieldType>& types) {
// In general, comparing street addresses with Equals, which uses ==, is not
// ideal since 3 Elm St and 3 Elm St. will be considered distinct. It's okay
// to use it here because near-duplicate addresses like this are filtered
// out before a LabelFormatter is created.
return HaveSameData(profiles, app_locale,
base::BindRepeating(&GetLabelStreetAddress, types),
base::BindRepeating(&Equals));
}
bool HasUnfocusedEmailField(FieldTypeGroup focused_group,
uint32_t form_groups) {
return ContainsEmail(form_groups) && focused_group != FieldTypeGroup::kEmail;
}
bool HasUnfocusedNameField(FieldTypeGroup focused_group, uint32_t form_groups) {
return ContainsName(form_groups) && focused_group != FieldTypeGroup::kName;
}
bool HasUnfocusedNonStreetAddressField(
ServerFieldType focused_field,
FieldTypeGroup focused_group,
const std::vector<ServerFieldType>& types) {
return HasNonStreetAddress(types) &&
(focused_group != FieldTypeGroup::kAddressHome ||
!IsNonStreetAddressPart(focused_field));
}
bool HasUnfocusedPhoneField(FieldTypeGroup focused_group,
uint32_t form_groups) {
return ContainsPhone(form_groups) &&
focused_group != FieldTypeGroup::kPhoneHome;
}
bool HasUnfocusedStreetAddressField(ServerFieldType focused_field,
FieldTypeGroup focused_group,
const std::vector<ServerFieldType>& types) {
return HasStreetAddress(types) &&
(focused_group != FieldTypeGroup::kAddressHome ||
!IsStreetAddressPart(focused_field));
}
bool FormHasOnlyNonStreetAddressFields(
const std::vector<ServerFieldType>& types,
uint32_t form_groups) {
return ContainsAddress(form_groups) && !HasStreetAddress(types) &&
!(ContainsName(form_groups) || ContainsPhone(form_groups) ||
ContainsEmail(form_groups));
}
} // namespace autofill
| 15,885 | 4,828 |
// Compute product of numbers in [1, 10)
#include <iostream>
int main(){
int sup = 10;
int start = 1;
int j = start;
for (int i = 1; i != sup; i++){
j *= i;
}
std::cout << j << std::endl;
return 0;
} | 241 | 98 |
/*
* hint:
* 素数相关的算法,包括:
* 使用 sqrt 来优化的素数判断函数
* 使用平方技巧来优化的素数判断函数
* 求素数表:埃氏筛法,Eratosthenes 筛法
*/
#include <iostream>
#include <cmath>
// 使用 sqrt 来优化的素数判断函数
// 需要 <cmath>
bool is_prime(int n)
{
for (int i = 2; i <= (int) sqrt(n * 1.0); i++)
if (n % i == 0)
return false;
return true;
}
// 使用平方技巧来优化的素数判断函数
// 缺点是若 n 较大,易产生溢出
bool is_prime_vice(int n)
{
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// 求素数表:埃氏筛法,Eratosthenes 筛法
// 时间复杂度 O(nloglogn)
#define MAXN 100 // 素数表大小
int prime[MAXN + 5], p_len = 0;
bool not_prime[MAXN * 20] = {};
// 找到 [2, n] 范围内的素数,保存至 prime[]
void find_prime(int n)
{
for (int i = 2; i <= n; i++)
if (not_prime[i] == false)
{
prime[p_len++] = i;
for (int j = i + i; j <= n; j += i)
not_prime[j] = true;
}
}
int main()
{
find_prime(MAXN);
for (int i = 0; i < p_len; i++)
printf(" %d", prime[i]);
} | 1,004 | 565 |
#include <QtWidgets>
#include <QScreen>
#include "mainwindow.h"
MainWindow::MainWindow()
{
this->setWindowIcon(QIcon(":/icons/testCADIcon.png"));
QStringList labels;
labels << tr(STRING_COMPONENTS) << " ≠" << tr(STRING_COMMENTS);
treeWidget = new QTreeWidget;
treeWidget->setHeaderLabels(labels);
treeWidget->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
treeWidget->header()->setSectionResizeMode(1,QHeaderView::ResizeToContents);
treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
setCentralWidget(treeWidget);
editor = new treeEditor(treeWidget);
analyzer = new treeAnalyzer(treeWidget);
icons = new iconsCatalog;
collector = 0;
combiner = 0;
sequencer = 0;
crossChecker = 0;
connect(treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), editor, SLOT(preventDiffColumnEdition(QTreeWidgetItem*,int)));
connect(treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(trackUnsavedChanges(QTreeWidgetItem*,int)));
connect(treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint)));
connect(treeWidget, SIGNAL(itemPressed(QTreeWidgetItem*,int)),this,SLOT(trackClicks(QTreeWidgetItem*)));
createActions();
createMenus();
createToolbars();
statusBar()->showMessage(QObject::tr(STRING_READY));
setWindowTitle(QObject::tr(STRING_TESTCAD));
QScreen *screen = QGuiApplication::primaryScreen();
QSize newSize = screen->availableSize();
newSize.setHeight(newSize.height()*0.8);
newSize.setWidth(newSize.width()*0.8);
resize(newSize);
hasChanges = false;
historyFilePath = QDir::currentPath() + "/" + STRING_HISTORY_FILE;
reloadOpenHistory();
}
//----------------------------------------------------------------------------------------------------
void MainWindow::addToOpenHistory(QString filePath)
{
QFile hFile (historyFilePath);
QTextStream history(&hFile);
QString hLine;
QStringList recentFiles;
if (hFile.exists()){
hFile.open(QFile::ReadWrite | QFile::Text );
hLine = history.readLine();
while (hLine.length() > 0){
recentFiles.append(hLine + '\n');
hLine = history.readLine();
}
hFile.remove();
}
hFile.open(QFile::WriteOnly | QFile::Text );
if (!recentFiles.contains(filePath + '\n')){
recentFiles.prepend(filePath + '\n');
}
for (int n = 0; n < recentFiles.length(); n++){
history << recentFiles.at(n);
if (n > 5)
break;
}
hFile.close();;
}
//----------------------------------------------------------------------------------------------------
void MainWindow::reloadOpenHistory()
{
QFile hFile (historyFilePath);
QTextStream history(&hFile);
QString hLine;
recentFiles.clear();
if (hFile.exists()){
hFile.open(QFile::ReadOnly | QFile::Text );
hLine = history.readLine();
while (hLine.length() > 0){
recentFiles.append(hLine);
hLine = history.readLine();
}
}
hFile.close();
historyMenu->clear();
for (int n = 0; n < recentFiles.length(); n++){
QAction *actBuff = historyMenu->addAction(recentFiles.at(n));
connect(actBuff, SIGNAL(triggered()), this, SLOT(openRecent()));
actBuff->setCheckable(true);
actBuff->setChecked(false);
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::openRecent()
{
for (int n = 0; n < historyMenu->actions().count(); n++){
QAction *actBuff = historyMenu->actions().at(n);
if (actBuff->isChecked()){
int decision = notSavedWarningResponse();
if(QMessageBox::Save == decision)
{
save();
treeWidget->clear();
openFromArgument(recentFiles.at(n));
hasChanges=false;
}else if(QMessageBox::Ignore == decision){
treeWidget->clear();
openFromArgument(recentFiles.at(n));
hasChanges=false;
}
}
actBuff->setChecked(false);
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::openFromArgument(QString filePathParam)
{
treeOpener opener(treeWidget, this);
opener.filePath = filePathParam;
if (opener.openSelected(treeOpener::toLoad)){
filePath = opener.filePath;
addToOpenHistory(filePath);
setWindowTitleToFileName();
statusBar()->showMessage(QObject::tr(STRING_FILE_LOADED),2000);
}else{
statusBar()->showMessage(QObject::tr(STRING_NO_FILE_LOADED),2000);
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::openTreeFor(int editionType)
{
if (editionType == editing){
treeWidget->clear();
}
treeOpener opener(treeWidget, this);
if (opener.fileOpened()){
if (editionType != appending){
filePath = opener.filePath;
addToOpenHistory(filePath);
setWindowTitleToFileName();
}
reloadOpenHistory();
statusBar()->showMessage(QObject::tr(STRING_FILE_LOADED),2000);
}else{
statusBar()->showMessage(QObject::tr(STRING_NO_FILE_LOADED),2000);
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::showSplashWindow()
{
splashWindow *spW = new splashWindow(this);
spW->show();
}
//----------------------------------------------------------------------------------------------------
void MainWindow::openDesignerWindow()
{
if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_COLLECTION){
if (collectorWindow::instance == 0){
collector = new collectorWindow(this, clickedItem);
connect(collector, SIGNAL(saved()), this, SLOT(save()));
collector->show();
}
}else if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_COMBINATION){
if (combinerWindow::instance == 0){
combiner = new combinerWindow(this, clickedItem);
connect(combiner, SIGNAL(saved()), this, SLOT(save()));
combiner->show();
}
}else if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_SEQUENCE){
if (sequencerWindow::instance == 0){
sequencer = new sequencerWindow(this, clickedItem);
connect(sequencer, SIGNAL(saved()), this, SLOT(save()));
sequencer->show();
}
}else if (clickedItem->data(0, Qt::UserRole).toString() == TAG_TYPE_TEST_CROSSCHECK){
if (crossCheckerWindow::instance == 0){
crossChecker = new crossCheckerWindow(this, clickedItem);
connect(crossChecker, SIGNAL(saved()), this, SLOT(save()));
crossChecker->show();
}
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::trackClicks(QTreeWidgetItem *item)
{
clickedItem = item;
editor->setClickedItem(item);
analyzer->setClickedItem(item);
if (collector != 0){
collectorWindow::clickedItem = item;
}
if (combiner != 0){
combinerWindow::clickedItem = item;
}
if (crossChecker != 0){
crossCheckerWindow::clickedItem = item;
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::showContextMenu(QPoint point)
{
Q_UNUSED(point);
QMenu contextMenu;
if ((editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_GROUP) &&
(editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_COLLECTION) &&
(editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_COMBINATION) &&
(editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_SEQUENCE) &&
(editor->getItemType(treeWidget->selectedItems().at(0))!=TAG_TYPE_TEST_CROSSCHECK)){
contextMenu.addAction(markPlannedAct);
contextMenu.addAction(markValidatedAct);
contextMenu.addAction(markReviewAct);
contextMenu.addAction(markPendingAct);
contextMenu.addAction(markFailed);
contextMenu.addAction(markUnsupported);
contextMenu.addSeparator();
contextMenu.addAction(copyPathClipAct);
contextMenu.addAction(copyBranchClipAct);
contextMenu.addSeparator();
contextMenu.addAction(collapseAct);
contextMenu.addAction(expandAct);
contextMenu.addSeparator();
contextMenu.addAction(addMultipleAct);
contextMenu.addSeparator();
contextMenu.addAction(copyVariableStats);
contextMenu.addSeparator();
contextMenu.addAction(copyAct);
contextMenu.addAction(cutAct);
contextMenu.addAction(pasteAct);
}else if (editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_GROUP){
contextMenu.addAction(addTestCollectionAct);
contextMenu.addAction(addTestCombinationAct);
contextMenu.addAction(addTestSequenceAct);
contextMenu.addAction(addTestCrossCheckerAct);
contextMenu.addSeparator();
contextMenu.addAction(collapseAct);
contextMenu.addAction(expandAct);
contextMenu.addSeparator();
contextMenu.addAction(pasteAct);
}else if ((editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_COLLECTION) ||
(editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_COMBINATION)||
(editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_SEQUENCE)||
(editor->getItemType(treeWidget->selectedItems().at(0)) == TAG_TYPE_TEST_CROSSCHECK)){
contextMenu.addAction(openTestDesignerAct);
contextMenu.addSeparator();
contextMenu.addAction(copyAct);
contextMenu.addAction(cutAct);
}
contextMenu.exec(QCursor::pos());
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createToolbars()
{
QToolBar *tb = this->addToolBar(tr(STRING_MENU_TOOLS));
tb->setMovable(false);
tb->addAction(openAct);
tb->addAction(saveAct);
tb->addAction(saveAsAct);
tb->addSeparator();
tb->addAction(addComponentAct);
tb->addSeparator();
tb->addAction(copyAct);
tb->addAction(cutAct);
tb->addAction(pasteAct);
tb->addAction(deleteAct);
tb->addAction(undoAct);
tb->addAction(moveUpAct);
tb->addAction(moveDownAct);
tb->addSeparator();
tb->addAction(searchAct);
tb->addAction(findFailedAct);
tb->addAction(findReviewAct);
tb->addAction(findUnsupportedAct);
tb->addAction(findPendingAct);
tb->addAction(findPlannedAct);
tb->addAction(findPassedAct);
tb->addAction(showStatsAct);
tb->addSeparator();
tb->addAction(addTestGroupAct);
tb->addAction(addTestCollectionAct);
tb->addAction(addTestCombinationAct);
tb->addAction(addTestSequenceAct);
tb->addAction(addTestCrossCheckerAct);
tb->addSeparator();
tb->addAction(clearHighlightsAct);
}
//----------------------------------------------------------------------------------------------------
void MainWindow::closeEvent(QCloseEvent *event)
{
int decision = notSavedWarningResponse();
bool deleteChildren = false;
if(QMessageBox::Save == decision)
{
save();
deleteChildren = true;
}else if(QMessageBox::Ignore == decision)
{
deleteChildren = true;
}else if(QMessageBox::Cancel == decision)
{
event->ignore();
}
if (deleteChildren){
if (collectorWindow::instance != 0)
delete(collector);
if (combinerWindow::instance != 0)
delete(combiner);
if (crossCheckerWindow::instance != 0)
delete(crossChecker);
if (sequencerWindow::instance != 0)
delete(sequencer);
event->accept();
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::exportImage()
{
treeSaver saver(treeWidget, this);
saver.exportTreeToImage();
}
//----------------------------------------------------------------------------------------------------
void MainWindow::clearHighlights()
{
treeEditor::clearHighlightsIn(treeWidget);
clearHighlightsAct->setVisible(false);
}
//----------------------------------------------------------------------------------------------------
void MainWindow::trackUnsavedChanges(QTreeWidgetItem *item, int column)
{
Q_UNUSED(item);
Q_UNUSED(column);
hasChanges = true;
}
//----------------------------------------------------------------------------------------------------
void MainWindow::compare()
{
treeOpener opener(treeWidget, this);
opener.selectToCompare();
analyzer->showDiffWith(opener.diffHashTable);
}
//----------------------------------------------------------------------------------------------------
void MainWindow::setWindowTitleToFileName()
{
if(!filePath.isEmpty()){
QFileInfo details;
details.setFile(filePath);
setWindowTitle(details.fileName());
}else{
setWindowTitle(QObject::tr(STRING_TESTCAD));
}
}
//----------------------------------------------------------------------------------------------------
int MainWindow::notSavedWarningResponse()
{
QMessageBox msgBox;
msgBox.setText(STRING_UNSAVEDCHANGES_DIALOG_TITLE);
msgBox.setInformativeText(STRING_SAVE_BEFORE);
msgBox.setIcon(QMessageBox::Warning);
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Ignore);
msgBox.setDefaultButton(QMessageBox::Save);
int decision = QMessageBox::Ignore;
if(hasChanges)
{
decision = msgBox.exec();
}
return decision;
}
//----------------------------------------------------------------------------------------------------
void MainWindow::show()
{
QMainWindow::show();
showSplashWindow();
}
//----------------------------------------------------------------------------------------------------
void MainWindow::open()
{
int decision = notSavedWarningResponse();
if(QMessageBox::Save == decision)
{
save();
hasChanges=false;
}else if(QMessageBox::Ignore == decision){
openTreeFor(editing);
hasChanges=false;
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::append()
{
openTreeFor(appending);
hasChanges=true;
}
//----------------------------------------------------------------------------------------------------
void MainWindow::save()
{
treeSaver saver(treeWidget, this);
if (!filePath.isEmpty()){
if(saver.saveTreeTo(filePath)){
statusBar()->showMessage(QObject::tr(STRING_FILE_SAVED),2000);
hasChanges = false;
}else{
statusBar()->showMessage(QObject::tr(STRING_FILE_NOT_SAVED),2000);
}
}else{
saveAs();
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::saveAs()
{
treeSaver saver(treeWidget, this);
if(saver.saveTreeAs()){
filePath = saver.filePath;
setWindowTitleToFileName();
statusBar()->showMessage(QObject::tr(STRING_FILE_SAVED),2000);
hasChanges = false;
}else{
statusBar()->showMessage(QObject::tr(STRING_FILE_NOT_SAVED),2000);
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::closeTree()
{
int decision = notSavedWarningResponse();
if(QMessageBox::Save == decision)
{
save();
hasChanges = false;
}else if(QMessageBox::Ignore == decision)
{
treeWidget->clear();
hasChanges = false;
}
}
//----------------------------------------------------------------------------------------------------
void MainWindow::about()
{
QMessageBox::about(this, tr(STRING_ABOUT_TESTCAD), tr(ABOUT_TEXT) + tr("Version:") + " " + tr(STRING_VERSION_NUMBER));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createActions()
{
createFileActions();
createInsertActions();
createEditActions();
createViewActions();
createToolsActions();
createTestActions();
createHelpActions();
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createFileActions()
{
openAct = new QAction(icons->openIcon,tr(STRING_ACTION_OPEN), this);
openAct->setShortcuts(QKeySequence::Open);
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
saveAct = new QAction(tr(STRING_ACTION_SAVE), this);
saveAct->setIcon(icons->saveIcon);
saveAct->setShortcuts(QKeySequence::Save);
connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
saveAsAct = new QAction(tr(STRING_ACTION_SAVE_AS), this);
saveAsAct->setShortcuts(QKeySequence::SaveAs);
saveAsAct->setIcon(icons->saveAsIcon);
connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
appendAct = new QAction(QIcon(":/icons/appendIcon.png"),tr(STRING_ACTION_APPEND), this);
connect(appendAct, SIGNAL(triggered()), this, SLOT(append()));
closeTreeAct = new QAction(tr("Close"), this);
connect(closeTreeAct, SIGNAL(triggered()), this, SLOT(closeTree()));
exitAct = new QAction(tr(STRING_ACTION_EXIT), this);
exitAct->setShortcuts(QKeySequence::Quit);
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createEditActions()
{
markPendingAct = new QAction(tr(STRING_ACTION_MARK_PENDING), this);
markPendingAct->setIcon(icons->pendingIcon);
markPendingAct->setShortcut(QKeySequence(tr("Ctrl+E")));
connect(markPendingAct, SIGNAL(triggered()), editor, SLOT(markAsPending()));
markPlannedAct = new QAction(tr(STRING_ACTION_MARK_PLANNED), this);
markPlannedAct->setIcon(icons->plannedIcon);
markPlannedAct->setShortcut(QKeySequence(tr("Ctrl+A")));
connect(markPlannedAct, SIGNAL(triggered()), editor, SLOT(markAsPlanned()));
markValidatedAct = new QAction(tr(STRING_ACTION_MARK_VALIDATED), this);
markValidatedAct->setIcon(icons->validatedIcon);
markValidatedAct->setShortcut(QKeySequence(tr("Ctrl+P")));
connect(markValidatedAct, SIGNAL(triggered()), editor, SLOT(markAsValidated()));
markReviewAct = new QAction(tr(STRING_ACTION_MARK_REVIEW), this);
markReviewAct->setIcon(icons->reviewIcon);
markReviewAct->setShortcut(QKeySequence(tr("Ctrl+R")));
connect(markReviewAct, SIGNAL(triggered()), editor, SLOT(markAsReview()));
markFailed = new QAction(tr(STRING_ACTION_MARK_FAILED), this);
markFailed->setIcon(icons->failedIcon);
markFailed->setShortcut(QKeySequence(tr("Ctrl+L")));
connect(markFailed, SIGNAL(triggered()), editor, SLOT(markAsFailed()));
markUnsupported = new QAction(tr(STRING_ACTION_MARK_UNSUPPORTED), this);
markUnsupported->setIcon(icons->unsupportedIcon);
connect(markUnsupported, SIGNAL(triggered()), editor, SLOT(markAsUnsupported()));
deleteAct = new QAction(tr(STRING_ACTION_DELETE), this);
deleteAct->setIcon(icons->deleteIcon);
deleteAct->setShortcut(QKeySequence::Delete);
connect(deleteAct, SIGNAL(triggered()), editor, SLOT(removeItem()));
undoAct = new QAction(tr(STRING_ACTION_UNDO), this);
undoAct->setIcon(icons->undoIcon);
undoAct->setShortcut(QKeySequence::Undo);
connect(undoAct, SIGNAL(triggered()), editor, SLOT(undo()));
copyAct = new QAction(tr(STRING_ACTION_COPY), this);
copyAct->setIcon(icons->copyIcon);
copyAct->setShortcut(QKeySequence::Copy);
connect(copyAct, SIGNAL(triggered()), editor, SLOT(copy()));
cutAct = new QAction(tr(STRING_ACTION_CUT), this);
cutAct->setIcon(icons->cutIcon);
cutAct->setShortcut(QKeySequence::Cut);
connect(cutAct, SIGNAL(triggered()), editor, SLOT(cut()));
pasteAct = new QAction(tr(STRING_ACTION_PASTE), this);
pasteAct->setIcon(icons->pasteIcon);
pasteAct->setShortcut(QKeySequence::Paste);
connect(pasteAct, SIGNAL(triggered()), editor, SLOT(paste()));
moveUpAct = new QAction(tr(STRING_ACTION_MOVE_UP), this);
moveUpAct->setIcon(icons->upIcon);
moveUpAct->setShortcut(QKeySequence(tr("Ctrl+U")));
connect(moveUpAct, SIGNAL(triggered()), editor, SLOT(moveUp()));
moveDownAct = new QAction(tr(STRING_ACTION_MOVE_DOWN), this);
moveDownAct->setIcon(icons->downIcon);
moveDownAct->setShortcut(QKeySequence(tr("Ctrl+D")));
connect(moveDownAct, SIGNAL(triggered()), editor, SLOT(moveDown()));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createInsertActions()
{
addComponentAct = new QAction(tr(STRING_ACTION_ADD_COMPONENT), this);
addComponentAct->setIcon(icons->addTopIcon);
connect(addComponentAct, SIGNAL(triggered()), editor, SLOT(addComponent()));
addMultipleAct = new QAction(tr(STRING_ACTION_ADD), this);
addMultipleAct->setIcon(icons->addIcon);
connect(addMultipleAct, SIGNAL(triggered()), editor, SLOT(addMultiple()));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createViewActions()
{
findFailedAct = new QAction(tr(STRING_ACTION_SHOW_FAILED), this);
findFailedAct->setIcon(icons->findFailedIcon);
connect(findFailedAct, SIGNAL(triggered()), editor, SLOT(showMissing()));
findReviewAct = new QAction(tr(STRING_ACTION_SHOW_REVIEW), this);
findReviewAct->setIcon(icons->findReviewIcon);
connect(findReviewAct, SIGNAL(triggered()), editor, SLOT(showReview()));
findPlannedAct = new QAction(tr(STRING_ACTION_SHOW_PLANNED), this);
findPlannedAct->setIcon(icons->findPlannedIcon);
connect(findPlannedAct, SIGNAL(triggered()), editor, SLOT(showPlanned()));
findPendingAct = new QAction(tr(STRING_ACTION_SHOW_PENDING), this);
findPendingAct->setIcon(icons->findPendingIcon);
connect(findPendingAct, SIGNAL(triggered()), editor, SLOT(showPending()));
findPassedAct = new QAction(tr(STRING_ACTION_SHOW_VALIDATED), this);
findPassedAct->setIcon(icons->findPassedIcon);
connect(findPassedAct, SIGNAL(triggered()), editor, SLOT(showValidated()));
findUnsupportedAct = new QAction(tr(STRING_ACTION_SHOW_UNSUPPORTED), this);
findUnsupportedAct->setIcon(icons->findUnsupportedIcon);
connect(findUnsupportedAct, SIGNAL(triggered()), editor, SLOT(showUnsupported()));
collapseAct = new QAction(tr(STRING_ACTION_COLLAPSE), this);
connect(collapseAct, SIGNAL(triggered()), editor, SLOT(collapseSelected()));
expandAct = new QAction(tr(STRING_ACTION_EXPAND), this);
connect(expandAct, SIGNAL(triggered()), editor, SLOT(expandSelected()));
collapseAllAct = new QAction(tr(STRING_ACTION_COLLAPSE_ALL), this);
connect(collapseAllAct, SIGNAL(triggered()), editor, SLOT(collapseAll()));
expandAllAct = new QAction(tr(STRING_ACTION_EXPAND_ALL), this);
connect(expandAllAct, SIGNAL(triggered()), editor, SLOT(expandAll()));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::search()
{
editor->search();
clearHighlightsAct->setVisible(true);
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createToolsActions()
{
searchAct = new QAction(tr(STRING_ACTION_SEARCH), this);
searchAct->setIcon(icons->searchIcon);
searchAct->setShortcut(QKeySequence::Find);
connect(searchAct, SIGNAL(triggered()), this, SLOT(search()));
copyPathClipAct = new QAction(QObject::tr(STRING_ACTION_COPY_PATH_TO_CLIPBOARD), this);
copyPathClipAct->setIcon(icons->pathIcon);
connect(copyPathClipAct, SIGNAL(triggered()), analyzer, SLOT(copyPathToClipBoard()));
copyBranchClipAct= new QAction(QObject::tr(STRING_ACTION_COPY_BRANCH_TO_CLIPBOARD), this);
copyBranchClipAct->setIcon(icons->copyBranchIcon);
connect(copyBranchClipAct, SIGNAL(triggered()), analyzer, SLOT(copyBranchToClipboard()));
showStatsAct = new QAction(QObject::tr(STRING_ACTION_SHOW_STATISTICS), this);
showStatsAct->setIcon(icons->statsIcon);
connect(showStatsAct, SIGNAL(triggered()), analyzer, SLOT(showStatistics()));
showDiffAct = new QAction(QObject::tr(STRING_ACTION_COMPARE), this);
connect(showDiffAct, SIGNAL(triggered()), this, SLOT(compare()));
exportImageAct = new QAction(icons->pictureIcon, QObject::tr(STRING_ACTION_EXPORT_IMAGE), this);
connect(exportImageAct, SIGNAL(triggered()), this, SLOT(exportImage()));
clearHighlightsAct = new QAction(QObject::tr(STRING_ACTION_CLEAR_HIGHLIGHTS), this);
clearHighlightsAct->setShortcut(QKeySequence(tr("Ctrl+H")));
clearHighlightsAct->setIcon(icons->clearHighlightsIcon);
clearHighlightsAct->setVisible(false);
connect(clearHighlightsAct, SIGNAL(triggered()), this, SLOT(clearHighlights()));
copyVariableStats = new QAction(QIcon(":/icons/statsIcon.png"),QObject::tr("Copy variable statistics"), this);
connect(copyVariableStats, SIGNAL(triggered()), analyzer, SLOT(copyVariableStatisticsToClipboard()));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createTestActions()
{
addTestGroupAct = new QAction(tr("Add a test group"), this);
addTestGroupAct->setIcon(icons->testGroupIcon);
connect(addTestGroupAct, SIGNAL(triggered()), editor, SLOT(addTestGroup()));
addTestCollectionAct = new QAction(tr("Add a collection"), this);
addTestCollectionAct->setIcon(icons->testCollectionIcon);
connect(addTestCollectionAct, SIGNAL(triggered()), editor, SLOT(addTestCollection()));
addTestCombinationAct = new QAction(tr("Add a combination"), this);
addTestCombinationAct->setIcon(icons->testCombinationIcon);
connect(addTestCombinationAct, SIGNAL(triggered()), editor, SLOT(addTestCombination()));
addTestSequenceAct = new QAction(tr("Add a sequence"), this);
addTestSequenceAct->setIcon(icons->testSequenceIcon);
connect(addTestSequenceAct, SIGNAL(triggered()), editor, SLOT(addTestSequence()));
openTestDesignerAct = new QAction(icons->designerIcon,tr("Open designer"), this);
connect(openTestDesignerAct, SIGNAL(triggered()), this, SLOT(openDesignerWindow()));
addTestCrossCheckerAct = new QAction(tr("Add a cross checker"), this);
addTestCrossCheckerAct->setIcon(icons->testCrossCheckerIcon);
connect(addTestCrossCheckerAct, SIGNAL(triggered()), editor, SLOT(addTestCrossChecker()));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createHelpActions()
{
aboutAct = new QAction(tr("About..."), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
//----------------------------------------------------------------------------------------------------
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("File"));
fileMenu->addAction(openAct);
fileMenu->addAction(saveAsAct);
fileMenu->addAction(saveAct);
fileMenu->addSeparator();
fileMenu->addAction(appendAct);
fileMenu->addSeparator();
fileMenu->addAction(closeTreeAct);
fileMenu->addAction(exitAct);
fileMenu->addSeparator();
historyMenu = new QMenu("Recent files...");
fileMenu->addMenu(historyMenu);
menuBar()->addSeparator();
editMenu = menuBar()->addMenu(tr("Edit"));
editMenu->addAction(addComponentAct);
editMenu->addSeparator();
editMenu->addAction(searchAct);
editMenu->addAction(moveUpAct);
editMenu->addAction(moveDownAct);
editMenu->addSeparator();
editMenu->addAction(markPlannedAct);
editMenu->addAction(markValidatedAct);
editMenu->addAction(markReviewAct);
editMenu->addAction(markPendingAct);
editMenu->addAction(markFailed);
editMenu->addAction(markUnsupported);
editMenu->addSeparator();
editMenu->addAction(copyAct);
editMenu->addAction(cutAct);
editMenu->addAction(pasteAct);
editMenu->addSeparator();
editMenu->addAction(deleteAct);
editMenu->addSeparator();
editMenu->addAction(undoAct);
menuBar()->addSeparator();
viewMenu = menuBar()->addMenu(tr("View"));
viewMenu->addAction(clearHighlightsAct);
editMenu->addSeparator();
viewMenu->addAction(findFailedAct);
viewMenu->addAction(findReviewAct);
viewMenu->addAction(findUnsupportedAct);
viewMenu->addAction(findPendingAct);
viewMenu->addAction(findPlannedAct);
viewMenu->addAction(findPassedAct);
viewMenu->addSeparator();
viewMenu->addAction(expandAllAct);
viewMenu->addAction(collapseAllAct);
viewMenu->addSeparator();
viewMenu->addAction(expandAct);
viewMenu->addAction(collapseAct);
menuBar()->addSeparator();
toolsMenu = menuBar()->addMenu(tr("Tools"));
toolsMenu->addAction(showStatsAct);
toolsMenu->addSeparator();
toolsMenu->addAction(exportImageAct);
toolsMenu->addSeparator();
toolsMenu->addAction(showDiffAct);
menuBar()->addSeparator();
testMenu = menuBar()->addMenu(tr("Test"));
testMenu->addAction(addTestGroupAct);
testMenu->addAction(addTestCollectionAct);
testMenu->addAction(addTestCombinationAct);
testMenu->addAction(addTestSequenceAct);
testMenu->addAction(addTestCrossCheckerAct);
testMenu->addSeparator();
menuBar()->addSeparator();
helpMenu = menuBar()->addMenu(tr("Help"));
helpMenu->addAction(aboutAct);
}
| 30,332 | 9,051 |
/*
* GridTools
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#pragma once
#include <oomph/communicator.hpp>
#include <oomph/util/moved_bit.hpp>
#include "./address.hpp"
#include <chrono>
#ifndef NDEBUG
#include <iostream>
#endif
namespace oomph
{
#define OOMPH_ANY_SOURCE (int)-1
struct endpoint_t
{
using rank_type = communicator::rank_type;
rank_type m_rank;
ucp_ep_h m_ep;
ucp_worker_h m_worker;
util::moved_bit m_moved;
endpoint_t() noexcept
: m_moved(true)
{
}
endpoint_t(rank_type rank, ucp_worker_h local_worker, const address_t& remote_worker_address)
: m_rank(rank)
, m_worker{local_worker}
{
ucp_ep_params_t ep_params;
ep_params.field_mask = UCP_EP_PARAM_FIELD_REMOTE_ADDRESS;
ep_params.address = remote_worker_address.get();
OOMPH_CHECK_UCX_RESULT(ucp_ep_create(local_worker, &ep_params, &(m_ep)));
}
endpoint_t(const endpoint_t&) = delete;
endpoint_t& operator=(const endpoint_t&) = delete;
endpoint_t(endpoint_t&& other) noexcept = default;
endpoint_t& operator=(endpoint_t&& other) noexcept
{
destroy();
m_ep.~ucp_ep_h();
::new ((void*)(&m_ep)) ucp_ep_h{other.m_ep};
m_rank = other.m_rank;
m_worker = other.m_worker;
m_moved = std::move(other.m_moved);
return *this;
}
~endpoint_t() { destroy(); }
void destroy()
{
if (!m_moved)
{
ucs_status_ptr_t ret = ucp_ep_close_nb(m_ep, UCP_EP_CLOSE_MODE_FLUSH);
if (UCS_OK == reinterpret_cast<std::uintptr_t>(ret)) return;
if (UCS_PTR_IS_ERR(ret)) return;
// wait untile the ep is destroyed, free the request
const auto t0 = std::chrono::system_clock::now();
double elapsed = 0.0;
static constexpr double t_timeout = 2000;
while (UCS_OK != ucp_request_check_status(ret))
{
elapsed =
std::chrono::duration<double, std::milli>(std::chrono::system_clock::now() - t0)
.count();
if (elapsed > t_timeout) break;
ucp_worker_progress(m_worker);
}
#ifndef NDEBUG
if (elapsed > t_timeout)
std::cerr << "WARNING: timeout waiting for UCX endpoint close" << std::endl;
#endif
ucp_request_free(ret);
}
}
//operator bool() const noexcept { return m_moved; }
operator ucp_ep_h() const noexcept { return m_ep; }
rank_type rank() const noexcept { return m_rank; }
ucp_ep_h& get() noexcept { return m_ep; }
const ucp_ep_h& get() const noexcept { return m_ep; }
};
} // namespace oomph
| 2,903 | 1,034 |
#include "TString.h"
#include "friendTreeInjector.h"
#include <iostream>
int main(int argc, char* argv[]){
if(argc<2) return -1;
TString infile = argv[1];
friendTreeInjector intree;
intree.addFromFile(infile);
intree.setSourceTreeName("tree");
intree.createChain();
auto c = intree.getChain();
std::cout << c->GetEntries() <<std::endl;
}
| 379 | 147 |
//
// main.cpp
// iomanip-demo
//
// Created by kai on 17/3/21.
// Copyright © 2017年 kai. All rights reserved.
//
#include <iostream>
#include <iomanip>
void test1() {
std::cout << std::setw(3) << 1 <<std::setw(3) << 10 << std::setw(3) << 100 << std::endl;
std::cout << std::setw(5) << 255 << std::endl;
std::cout << std::setfill('@') << std::setw(5) << 255 << std::endl;
std::cout << std::setfill('*') << std::setw(6) << 123 << 456 << std::endl;
std::cout << std::setbase(8) << std::setw(5) << 255 << std::endl;
std::cout << std::setbase(10) << std::setw(5) << 255 << std::endl;
std::cout << std::setbase(16) << std::setw(5) << 255 << std::endl;
std::cout << 12345.0 << std::endl; //输出12345
std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(3) << 1.2345 << std::endl; //输出1.234(遵循四舍六入五成双原则,而不是四舍五入原则)
std::cout << std::resetiosflags(std::ios::fixed) << std::endl; //需要用resetiosflags()函数清楚前面的输出格式
std::cout << std::setiosflags(std::ios::scientific) << 12345.0 << std::endl; //输出1.234e+04
std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(3) << 12345.0 << std::endl; //输出1.234e+04
}
int main(int argc, const char * argv[]) {
test1();
std::cout << "Hello, World!\n";
return 0;
}
| 1,325 | 623 |
/*
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int minPathSum(vector<vector<int>> & grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = grid[0][0];
for (int j = 1; j < n; ++j)
dp[0][j] = grid[0][j] + dp[0][j-1];
for (int i = 1; i < m; ++i) {
dp[i][0] = grid[i][0] + dp[i-1][0];
for (int j = 1; j < n; ++j) {
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[m-1][n-1];
}
};
int main() {
Solution sol = Solution();
freopen("data.in", "r", stdin);
int m, n, t;
cin >> m >> n;
vector<vector<int>> grid(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
cin >> t;
grid[i][j] = t;
}
cout << sol.minPathSum(grid) << endl;
return 0;
} | 1,318 | 536 |
#include "pch.h"
#include "framework.h"
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "Time.h"
#include "StrBufs.h"
#include "client.h"
#include "banned.h" //must include last
int g_RequestRateLimit_ms = 100;
namespace cro = std::chrono;
cro::steady_clock::time_point g_NextRequestTp = cro::steady_clock::now();
bool can_request_now() { return cro::steady_clock::now() > g_NextRequestTp; }
bool delay_request(bool double_delay) {
auto limit_ms = g_RequestRateLimit_ms;
if (double_delay) limit_ms *= 2;
while (!can_request_now()) {
cl_drain();
if (!refresh()) return false;
cl_loiter();
}
g_NextRequestTp = cro::steady_clock::now() + cro::milliseconds(limit_ms);
return true;
}
DATE vEpochSeconds_to_date(double vEpochSeconds){
return vEpochSeconds / (24ll * 60ll * 60ll) + 25569ll; // 25569. = DATE(1.1.1970 00:00)
}
DATE llEpochMicroseconds_to_date(long long llEpochMicroseconds) {
return ((double)llEpochMicroseconds) / (1000000ll * (24ll * 60ll * 60ll)) + 25569ll; // 25569. = DATE(1.1.1970 00:00)
}
double date_to_vEpochSeconds(DATE date){
return (double)((date - 25569ll) * (24ll * 60ll * 60ll));
}
void set_time_zone(const char* sTZ) {
_putenv_s("TZ", sTZ);
_tzset();
return;
}
int epochmilli_str_to_yyyymmdd(const char* emilli) {
__time32_t t32 = (__time32_t)(strtod(emilli, NULL) / 1000);
if (!t32) return 0; // parse failure
struct tm tm1 = { 0 };
set_time_zone("UTC0");
if (_localtime32_s(&tm1, &t32)) {
return 0;// error
}
int y = tm1.tm_year + 1900;
int m = tm1.tm_mon + 1;
int d = tm1.tm_mday;
return y * 10000 + m * 100 + d;
}
int get_todays_date_yyyymmdd() {
__time32_t t32 = 0;
struct tm tm1 = { 0 };
_time32(&t32);
set_time_zone("UTC0");
_localtime32_s(&tm1, &t32);
int y = tm1.tm_year + 1900;
int m = tm1.tm_mon + 1;
int d = tm1.tm_mday;
return y * 10000 + m * 100 + d;
}
int vEpochSeconds_to_todays_date_yyyymmdd(double vEpochSeconds) {
__time32_t t32 = lround(vEpochSeconds);
struct tm tm1 = { 0 };
set_time_zone("UTC0");
_localtime32_s(&tm1, &t32);
int y = tm1.tm_year + 1900;
int m = tm1.tm_mon + 1;
int d = tm1.tm_mday;
return y * 10000 + m * 100 + d;
}
char get_monthchar(int monthnum) { //0=jan, 1=feb ... 11=dec.
switch (monthnum) {
case 0: return 'F';//jan
case 1: return 'G';//feb
case 2: return 'H';
case 3: return 'J';
case 4: return 'K';
case 5: return 'M';
case 6: return 'N';
case 7: return 'Q';
case 8: return 'U';
case 9: return 'V';
case 10: return 'X';
case 11: return 'Z'; //dec
default: return '_'; //fail
}
}
const char* get_monthcode_string(int month_flags) {
static char out[13];
memset(out, 0, 13);
int i = 0;
char ch[2] = { 0,0 };
for (i = 0; i < 12; i++) {
if ((1 << i) & month_flags) {
ch[0] = get_monthchar(i);
strcat_s(out,13, ch);
}
}
return out;
} | 2,980 | 1,466 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include "keto/router_db/Constants.hpp"
namespace keto {
namespace router_db {
const char* Constants::ROUTER_INDEX = "routes";
const std::vector<std::string> Constants::DB_LIST =
{Constants::ROUTER_INDEX};
}
}
| 423 | 133 |
typedef int my_cb(int dst, int len, int dat);
int f(my_cb cb, void *dat);
int f(my_cb cb, void *dat)
{
return 0;
}
| 117 | 54 |
//===--- CIndexStoreDB.cpp ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "CIndexStoreDB/CIndexStoreDB.h"
#include "IndexStoreDB/Index/IndexStoreLibraryProvider.h"
#include "IndexStoreDB/Index/IndexSystem.h"
#include "IndexStoreDB/Index/IndexSystemDelegate.h"
#include "IndexStoreDB/Core/Symbol.h"
#include "indexstore/IndexStoreCXX.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include <Block.h>
using namespace IndexStoreDB;
using namespace index;
class IndexStoreDBObjectBase
: public llvm::ThreadSafeRefCountedBase<IndexStoreDBObjectBase> {
public:
virtual ~IndexStoreDBObjectBase() {}
};
template <typename T>
class IndexStoreDBObject: public IndexStoreDBObjectBase {
public:
T value;
IndexStoreDBObject(T value) : value(std::move(value)) {}
};
template <typename T>
static IndexStoreDBObject<T> *make_object(const T &value) {
auto obj = new IndexStoreDBObject<T>(value);
obj->Retain();
return obj;
}
struct IndexStoreDBError {
std::string message;
IndexStoreDBError(StringRef message) : message(message.str()) {}
};
class BlockIndexStoreLibraryProvider : public IndexStoreLibraryProvider {
indexstore_library_provider_t callback;
public:
BlockIndexStoreLibraryProvider(indexstore_library_provider_t callback)
: callback(Block_copy(callback)) {}
~BlockIndexStoreLibraryProvider() {
Block_release(callback);
}
IndexStoreLibraryRef getLibraryForStorePath(StringRef storePath) override {
indexstore_functions_t api;
if (auto lib = callback(storePath.str().c_str())) {
auto *obj = (IndexStoreDBObject<IndexStoreLibraryRef> *)lib;
return obj->value;
} else {
return nullptr;
}
}
};
indexstoredb_index_t
indexstoredb_index_create(const char *storePath, const char *databasePath,
indexstore_library_provider_t libProvider,
// delegate,
bool readonly, indexstoredb_error_t *error) {
auto delegate = std::make_shared<IndexSystemDelegate>();
auto libProviderObj = std::make_shared<BlockIndexStoreLibraryProvider>(libProvider);
std::string errMsg;
if (auto index =
IndexSystem::create(storePath, databasePath, libProviderObj, delegate,
readonly, llvm::None, errMsg)) {
return make_object(index);
} else if (error) {
*error = (indexstoredb_error_t)new IndexStoreDBError(errMsg);
}
return nullptr;
}
indexstoredb_indexstore_library_t
indexstoredb_load_indexstore_library(const char *dylibPath,
indexstoredb_error_t *error) {
std::string errMsg;
if (auto lib = loadIndexStoreLibrary(dylibPath, errMsg)) {
return make_object(lib);
} else if (error) {
*error = (indexstoredb_error_t)new IndexStoreDBError(errMsg);
}
return nullptr;
}
bool
indexstoredb_index_symbol_occurrences_by_usr(
indexstoredb_index_t index,
const char *usr,
uint64_t roles,
indexstoredb_symbol_occurrence_receiver_t receiver)
{
auto obj = (IndexStoreDBObject<std::shared_ptr<IndexSystem>> *)index;
return obj->value->foreachSymbolOccurrenceByUSR(usr, (SymbolRoleSet)roles,
[&](SymbolOccurrenceRef Occur) -> bool {
return receiver(make_object(Occur));
});
}
bool
indexstoredb_index_related_symbol_occurrences_by_usr(
indexstoredb_index_t index,
const char *usr,
uint64_t roles,
indexstoredb_symbol_occurrence_receiver_t receiver)
{
auto obj = (IndexStoreDBObject<std::shared_ptr<IndexSystem>> *)index;
return obj->value->foreachRelatedSymbolOccurrenceByUSR(usr, (SymbolRoleSet)roles,
[&](SymbolOccurrenceRef Occur) -> bool {
return receiver(make_object(Occur));
});
}
const char *
indexstoredb_symbol_usr(indexstoredb_symbol_t symbol) {
auto obj = (IndexStoreDBObject<std::shared_ptr<Symbol>> *)symbol;
return obj->value->getUSR().c_str();
}
const char *
indexstoredb_symbol_name(indexstoredb_symbol_t symbol) {
auto obj = (IndexStoreDBObject<std::shared_ptr<Symbol>> *)symbol;
return obj->value->getName().c_str();
}
indexstoredb_symbol_t
indexstoredb_symbol_occurrence_symbol(indexstoredb_symbol_occurrence_t occur) {
auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur;
return make_object(obj->value->getSymbol());
}
uint64_t
indexstoredb_symbol_occurrence_roles(indexstoredb_symbol_occurrence_t occur) {
auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur;
return (uint64_t)obj->value->getRoles();
}
indexstoredb_symbol_location_t indexstoredb_symbol_occurrence_location(
indexstoredb_symbol_occurrence_t occur) {
auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur;
return (indexstoredb_symbol_location_t)&obj->value->getLocation();
}
const char *
indexstoredb_symbol_location_path(indexstoredb_symbol_location_t loc) {
auto obj = (SymbolLocation *)loc;
return obj->getPath().getPathString().c_str();
}
bool
indexstoredb_symbol_location_is_system(indexstoredb_symbol_location_t loc) {
auto obj = (SymbolLocation *)loc;
return obj->isSystem();
}
int
indexstoredb_symbol_location_line(indexstoredb_symbol_location_t loc) {
auto obj = (SymbolLocation *)loc;
return obj->getLine();
}
int
indexstoredb_symbol_location_column_utf8(indexstoredb_symbol_location_t loc) {
auto obj = (SymbolLocation *)loc;
return obj->getColumn();
}
indexstoredb_object_t indexstoredb_retain(indexstoredb_object_t obj) {
if (obj)
((IndexStoreDBObjectBase *)obj)->Retain();
return obj;
}
void
indexstoredb_release(indexstoredb_object_t obj) {
if (obj)
((IndexStoreDBObjectBase *)obj)->Release();
}
const char *
indexstoredb_error_get_description(indexstoredb_error_t error) {
return ((IndexStoreDBError *)error)->message.c_str();
}
void
indexstoredb_error_dispose(indexstoredb_error_t error) {
if (error)
delete (IndexStoreDBError *)error;
}
| 6,289 | 2,040 |
/***************************************************************************
*
* Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved.
*
* File: dsbuf.cpp
* Content: DirectSound Buffer object
* History:
* Date By Reason
* ==== == ======
* 12/27/96 dereks Created
* 1999-2001 duganp Many changes, fixes and updates
*
***************************************************************************/
#include "dsoundi.h"
inline DWORD DSBCAPStoDSBPLAY(DWORD dwCaps) {return (dwCaps >> 1) & DSBPLAY_LOCMASK;}
inline DWORD DSBCAPStoDSBSTATUS(DWORD dwCaps) {return (dwCaps << 1) & DSBSTATUS_LOCMASK;}
inline DWORD DSBPLAYtoDSBCAPS(DWORD dwPlay) {return (dwPlay << 1) & DSBCAPS_LOCMASK;}
inline DWORD DSBPLAYtoDSBSTATUS(DWORD dwPlay) {return (dwPlay << 2) & DSBSTATUS_LOCMASK;}
inline DWORD DSBSTATUStoDSBCAPS(DWORD dwStatus) {return (dwStatus >> 1) & DSBCAPS_LOCMASK;}
inline DWORD DSBSTATUStoDSBPLAY(DWORD dwStatus) {return (dwStatus >> 2) & DSBPLAY_LOCMASK;}
/***************************************************************************
*
* CDirectSoundBuffer
*
* Description:
* DirectSound buffer object constructor.
*
* Arguments:
* CDirectSound * [in]: parent object.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundBuffer::CDirectSoundBuffer"
CDirectSoundBuffer::CDirectSoundBuffer(CDirectSound *pDirectSound)
{
DPF_ENTER();
DPF_CONSTRUCT(CDirectSoundBuffer);
// Initialize defaults
m_pDirectSound = pDirectSound;
m_dwStatus = 0;
InitStruct(&m_dsbd, sizeof(m_dsbd));
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* ~CDirectSoundBuffer
*
* Description:
* DirectSound buffer object destructor.
*
* Arguments:
* (void)
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundBuffer::~CDirectSoundBuffer"
CDirectSoundBuffer::~CDirectSoundBuffer(void)
{
DPF_ENTER();
DPF_DESTRUCT(CDirectSoundBuffer);
// Free memory
MEMFREE(m_dsbd.lpwfxFormat);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* UpdateBufferStatusFlags
*
* Description:
* Converts a set of VAD_BUFFERSTATE_* flags to DSBSTATUS_* flags.
*
* Arguments:
* DWORD [in]: VAD_BUFFERSTATE_* flags.
* LPDWORD [in/out]: current buffer flags.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundBuffer::UpdateBufferStatusFlags"
void CDirectSoundBuffer::UpdateBufferStatusFlags(DWORD dwState, LPDWORD pdwStatus)
{
const DWORD dwStateMask = VAD_BUFFERSTATE_STARTED | VAD_BUFFERSTATE_LOOPING;
DPF_ENTER();
dwState &= dwStateMask;
if(!(dwState & VAD_BUFFERSTATE_STARTED))
{
ASSERT(!(dwState & VAD_BUFFERSTATE_LOOPING));
dwState &= ~VAD_BUFFERSTATE_LOOPING;
}
if(dwState & VAD_BUFFERSTATE_STARTED)
{
*pdwStatus |= DSBSTATUS_PLAYING;
}
else
{
*pdwStatus &= ~DSBSTATUS_PLAYING;
}
if(dwState & VAD_BUFFERSTATE_LOOPING)
{
*pdwStatus |= DSBSTATUS_LOOPING;
}
else
{
*pdwStatus &= ~DSBSTATUS_LOOPING;
}
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* CDirectSoundPrimaryBuffer
*
* Description:
* DirectSound primary buffer object constructor.
*
* Arguments:
* CDirectSound * [in]: pointer to the parent object.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::CDirectSoundPrimaryBuffer"
CDirectSoundPrimaryBuffer::CDirectSoundPrimaryBuffer(CDirectSound *pDirectSound)
: CDirectSoundBuffer(pDirectSound)
{
DPF_ENTER();
DPF_CONSTRUCT(CDirectSoundPrimaryBuffer);
// Initialize defaults
m_pImpDirectSoundBuffer = NULL;
m_pDeviceBuffer = NULL;
m_p3dListener = NULL;
m_pPropertySet = NULL;
m_dwRestoreState = VAD_BUFFERSTATE_STOPPED | VAD_BUFFERSTATE_WHENIDLE;
m_fWritePrimary = FALSE;
m_ulUserRefCount = 0;
m_hrInit = DSERR_UNINITIALIZED;
m_bDataLocked = FALSE;
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* ~CDirectSoundPrimaryBuffer
*
* Description:
* DirectSound primary buffer object destructor.
*
* Arguments:
* (void)
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::~CDirectSoundPrimaryBuffer"
CDirectSoundPrimaryBuffer::~CDirectSoundPrimaryBuffer(void)
{
DPF_ENTER();
DPF_DESTRUCT(CDirectSoundBuffer);
// Make sure to give up WRITEPRIMARY access
if(m_pDeviceBuffer)
{
SetPriority(DSSCL_NONE);
}
// Free all interfaces
DELETE(m_pImpDirectSoundBuffer);
// Free owned objects
ABSOLUTE_RELEASE(m_p3dListener);
ABSOLUTE_RELEASE(m_pPropertySet);
// Free the device buffer
RELEASE(m_pDeviceBuffer);
// The owning DirectSound object is responsible for updating the global
// focus state.
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* Initialize
*
* Description:
* Initializes a buffer object. If this function fails, the object
* should be immediately deleted.
*
* Arguments:
* LPDSBUFFERDESC [in]: buffer description.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Initialize"
HRESULT CDirectSoundPrimaryBuffer::Initialize(LPCDSBUFFERDESC pDesc)
{
VADRBUFFERCAPS vrbc;
HRESULT hr;
DPF_ENTER();
ASSERT(IsInit() == DSERR_UNINITIALIZED);
ASSERT(pDesc);
// Create the device buffer
hr = m_pDirectSound->m_pDevice->CreatePrimaryBuffer(pDesc->dwFlags, m_pDirectSound, &m_pDeviceBuffer);
// Attempt to create the property set object
if(SUCCEEDED(hr))
{
m_pPropertySet = NEW(CDirectSoundPropertySet(this));
hr = HRFROMP(m_pPropertySet);
if(SUCCEEDED(hr))
{
hr = m_pPropertySet->Initialize();
}
if(SUCCEEDED(hr))
{
// We don't care if this fails
m_pPropertySet->AcquireResources(m_pDeviceBuffer);
}
}
// Attempt to create the 3D listener
if(SUCCEEDED(hr) && (pDesc->dwFlags & DSBCAPS_CTRL3D))
{
m_p3dListener = NEW(CDirectSound3dListener(this));
hr = HRFROMP(m_p3dListener);
if(SUCCEEDED(hr))
{
hr = m_p3dListener->Initialize(m_pDeviceBuffer);
}
}
// Register the standard buffer interface with the interface manager
if(SUCCEEDED(hr))
{
hr = CreateAndRegisterInterface(this, IID_IDirectSoundBuffer, this, &m_pImpDirectSoundBuffer);
}
// Build the local buffer description
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->GetCaps(&vrbc);
}
if(SUCCEEDED(hr))
{
m_dsbd.dwFlags = (vrbc.dwFlags & DSBCAPS_LOCMASK);
m_dsbd.dwBufferBytes = vrbc.dwBufferBytes;
m_dsbd.lpwfxFormat = AllocDefWfx();
hr = HRFROMP(m_dsbd.lpwfxFormat);
}
// If the 3D listener has been created, he's already registered the
// 3D listener interface.
if(SUCCEEDED(hr) && m_p3dListener)
{
m_dsbd.dwFlags |= DSBCAPS_CTRL3D;
}
// Handle buffer caps flags change
if(SUCCEEDED(hr))
{
hr = SetBufferFlags(pDesc->dwFlags);
}
// Handle priority change
if(SUCCEEDED(hr))
{
hr = SetPriority(m_pDirectSound->m_dsclCooperativeLevel.dwPriority);
}
// The DirectSound object creating this buffer is responsible for updating
// the global focus state.
// Success
if(SUCCEEDED(hr))
{
m_hrInit = DS_OK;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetCaps
*
* Description:
* Queries capabilities for the buffer.
*
* Arguments:
* LPDSBCAPS [out]: receives caps.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetCaps"
HRESULT CDirectSoundPrimaryBuffer::GetCaps(LPDSBCAPS pDsbCaps)
{
DPF_ENTER();
ASSERT(LXOR(m_dsbd.dwFlags & DSBCAPS_LOCSOFTWARE, m_dsbd.dwFlags & DSBCAPS_LOCHARDWARE));
pDsbCaps->dwFlags = m_dsbd.dwFlags;
pDsbCaps->dwBufferBytes = m_dsbd.dwBufferBytes;
pDsbCaps->dwUnlockTransferRate = 0;
pDsbCaps->dwPlayCpuOverhead = 0;
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
/***************************************************************************
*
* OnCreateSoundBuffer
*
* Description:
* Called in response to an application calling
* CreateSoundBuffer(DSBCAPS_PRIMARYBUFFER).
*
* Arguments:
* DWORD [in]: new buffer flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::OnCreateSoundBuffer"
HRESULT CDirectSoundPrimaryBuffer::OnCreateSoundBuffer(DWORD dwFlags)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// COMPATCOMPAT: in previous versions of DirectSound, calling
// CreateSoundBuffer(PRIMARYBUFFER) once would change the buffer flags,
// but calling it twice would just return a pointer to the same,
// unmodified buffer. I've introduced new behavior in this version
// that would allow an app to modify the capabilities of the primary
// buffer on-the-fly by calling CreateSoundBuffer(PRIMARYBUFFER) more
// than once. This could potentially free interfaces that the app
// will later try to use. One way to fix this would be to add a data
// member to the DirectSound or primary buffer object that stores
// whether or not the application has created a primary buffer already.
// The steps outlined above are now implemented here:
if(m_ulUserRefCount)
{
RPF((dwFlags == m_dsbd.dwFlags) ? DPFLVL_WARNING : DPFLVL_ERROR, "The primary buffer already exists. Any changes made to the buffer description will be ignored.");
}
else
{
hr = SetBufferFlags(dwFlags);
}
if(SUCCEEDED(hr))
{
AddRef();
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetBufferFlags
*
* Description:
* Changes capabilities for the buffer. This function is also
* responsible for creating and freeing interfaces.
*
* Arguments:
* DWORD [in]: new buffer flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetBufferFlags"
HRESULT CDirectSoundPrimaryBuffer::SetBufferFlags(DWORD dwFlags)
{
HRESULT hr = DS_OK;
DWORD dwVolPanCaps;
DPF_ENTER();
// Make sure we can handle the requested flags
if((dwFlags & DSBCAPS_CTRL3D) && !m_p3dListener)
{
RPF(DPFLVL_ERROR, "No 3D listener support");
hr = DSERR_CONTROLUNAVAIL;
}
// Not all capabilities of the DirectSound primary buffer map to the
// methods of the device primary buffer. Specifically, attenuation is
// handled by the render device. Let's check these flags before
// proceeding.
if(SUCCEEDED(hr) && (dwFlags & DSBCAPS_CTRLATTENUATION))
{
hr = m_pDirectSound->m_pDevice->GetVolumePanCaps(&dwVolPanCaps);
if(SUCCEEDED(hr) && (dwFlags & DSBCAPS_CTRLVOLUME) && !(dwVolPanCaps & DSBCAPS_CTRLVOLUME))
{
RPF(DPFLVL_ERROR, "The device does not support CTRLVOLUME");
hr = DSERR_CONTROLUNAVAIL;
}
if(SUCCEEDED(hr) && (dwFlags & DSBCAPS_CTRLPAN) && !(dwVolPanCaps & DSBCAPS_CTRLPAN))
{
RPF(DPFLVL_ERROR, "The device does not support CTRLPAN");
hr = DSERR_CONTROLUNAVAIL;
}
}
// Fix up the 3D listener interface
if(SUCCEEDED(hr) && ((m_dsbd.dwFlags & DSBCAPS_CTRL3D) != (dwFlags & DSBCAPS_CTRL3D)))
{
if(dwFlags & DSBCAPS_CTRL3D)
{
DPF(DPFLVL_INFO, "Primary buffer becoming CTRL3D. Registering IID_IDirectSound3DListener");
hr = RegisterInterface(IID_IDirectSound3DListener, m_p3dListener->m_pImpDirectSound3dListener, m_p3dListener->m_pImpDirectSound3dListener);
}
else
{
DPF(DPFLVL_INFO, "Primary buffer becoming ~CTRL3D. Unregistering IID_IDirectSound3DListener");
hr = UnregisterInterface(IID_IDirectSound3DListener);
}
}
// Save buffer flags. We're assuming that the buffer location has
// already been saved to m_dsbd.dwFlags at this point.
if(SUCCEEDED(hr))
{
m_dsbd.dwFlags = (dwFlags & ~DSBCAPS_LOCMASK) | (m_dsbd.dwFlags & DSBCAPS_LOCMASK);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetFormat
*
* Description:
* Retrieves the format for the given buffer.
*
* Arguments:
* LPWAVEFORMATEX [out]: receives the format.
* LPDWORD [in/out]: size of the format structure. On entry, this
* must be initialized to the size of the structure.
* On exit, this will be filled with the size that
* was required.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetFormat"
HRESULT CDirectSoundPrimaryBuffer::GetFormat(LPWAVEFORMATEX pwfxFormat, LPDWORD pdwSize)
{
HRESULT hr;
DPF_ENTER();
hr = CopyWfxApi(m_dsbd.lpwfxFormat, pwfxFormat, pdwSize);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetFormat
*
* Description:
* Sets the format for a given buffer.
*
* Arguments:
* LPWAVEFORMATEX [in]: new format.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetFormat"
HRESULT CDirectSoundPrimaryBuffer::SetFormat(LPCWAVEFORMATEX pwfxFormat)
{
LPWAVEFORMATEX pwfxLocal = NULL;
BOOL fActive = MAKEBOOL(m_dwStatus & DSBSTATUS_ACTIVE);
HRESULT hr = DS_OK;
CNode<CDirectSound *> * pNode;
BOOL bRewriteStartupSilence = FALSE;
DPF_ENTER();
// Check access rights
if(m_pDirectSound->m_dsclCooperativeLevel.dwPriority < DSSCL_PRIORITY)
{
RPF(DPFLVL_ERROR, "Cooperative level is not PRIORITY");
hr = DSERR_PRIOLEVELNEEDED;
}
// Save a local copy of the format
if(SUCCEEDED(hr))
{
pwfxLocal = CopyWfxAlloc(pwfxFormat);
hr = HRFROMP(pwfxLocal);
}
// We can only change the format if we're active
if(SUCCEEDED(hr) && !fActive)
{
// The Administrator says we're out of focus. If there's not really anyone
// else in focus, we're going to cheat and set the format anyway.
// DuganP: This is weird - presumably done so fewer apps will break when the
// user switches focus away from them temporarily. There's the problem that
// if multiple apps are in this state, whoever's last to set the format wins.
// However, app-compat probably means we can't touch this code any more, so...
for(pNode = g_pDsAdmin->m_lstDirectSound.GetListHead(); pNode; pNode = pNode->m_pNext)
{
if(pNode->m_data && SUCCEEDED(pNode->m_data->IsInit()))
{
if(pNode->m_data->m_pPrimaryBuffer && this != pNode->m_data->m_pPrimaryBuffer && SUCCEEDED(pNode->m_data->m_pPrimaryBuffer->IsInit()))
{
if(DSBUFFERFOCUS_INFOCUS == g_pDsAdmin->GetBufferFocusState(pNode->m_data->m_pPrimaryBuffer))
{
// NOTE: We added a "&& pNode->m_data->GetOwnerProcessId() != GetOwnerProcessId())"
// clause to fix WinME bug 120317, and we removed it again to fix DX8 bug 40627.
// We found an in-focus primary buffer [in another app], so fail.
break;
}
}
}
}
if(!pNode)
{
fActive = TRUE;
}
}
// Apply the format to the device
if(SUCCEEDED(hr))
{
if( m_fWritePrimary )
{
//
// See if this a WRITEPRIMARY app that's about to change to a new sample size.
// If so, silence will need to be re-written for the new sample size
// (providing the app hasn't locked any data yet).
//
LPWAVEFORMATEX pwfxOld;
DWORD dwSize;
HRESULT hrTmp = m_pDirectSound->m_pDevice->GetGlobalFormat(NULL, &dwSize);
if(SUCCEEDED(hrTmp))
{
pwfxOld = (LPWAVEFORMATEX)MEMALLOC_A(BYTE, dwSize);
if( pwfxOld )
{
hrTmp = m_pDirectSound->m_pDevice->GetGlobalFormat(pwfxOld, &dwSize);
if( SUCCEEDED( hr ) )
{
if( pwfxLocal->wBitsPerSample != pwfxOld->wBitsPerSample )
{
bRewriteStartupSilence = TRUE;
}
}
MEMFREE(pwfxOld);
}
}
}
if(fActive)
{
DPF(DPFLVL_INFO, "Setting the format on device " DPF_GUID_STRING, DPF_GUID_VAL(m_pDirectSound->m_pDevice->m_pDeviceDescription->m_guidDeviceId));
// If we're WRITEPRIMARY, the format needs to be exact. Otherwise,
// we'll try to set the next closest format. We're checking the
// actual focus priority instead of our local writeprimary flag
// in case the buffer is lost.
if(DSSCL_WRITEPRIMARY == m_pDirectSound->m_dsclCooperativeLevel.dwPriority)
{
hr = m_pDirectSound->SetDeviceFormatExact(pwfxLocal);
}
else
{
hr = m_pDirectSound->SetDeviceFormat(pwfxLocal);
}
}
else
{
DPF(DPFLVL_INFO, "NOT setting the format on device " DPF_GUID_STRING, DPF_GUID_VAL(m_pDirectSound->m_pDevice->m_pDeviceDescription->m_guidDeviceId));
}
}
// Update the stored format
if(SUCCEEDED(hr))
{
MEMFREE(m_dsbd.lpwfxFormat);
m_dsbd.lpwfxFormat = pwfxLocal;
if( bRewriteStartupSilence && !m_bDataLocked )
{
// Refill the buffer with silence in the new sample size format,
// only if the primary buffer was started playing before Locking any data.
DSBUFFERFOCUS bfFocus = g_pDsAdmin->GetBufferFocusState(this);
if( bfFocus == DSBUFFERFOCUS_INFOCUS)
{
ASSERT( m_fWritePrimary );
// Request write access first
HRESULT hrTmp = m_pDeviceBuffer->RequestWriteAccess(TRUE);
if(SUCCEEDED(hrTmp))
{
// Fill the buffer with silence. At this point, we MUST be WRITEPRIMARY.
::FillSilence(m_pDeviceBuffer->m_pSysMemBuffer->GetPlayBuffer(), m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat->wBitsPerSample);
hrTmp = m_pDeviceBuffer->CommitToDevice(0, m_pDeviceBuffer->m_pSysMemBuffer->GetSize());
#ifdef DEBUG
if(FAILED( hrTmp ) )
{
// Not a catastrophic failure if we fail this
DPF(DPFLVL_WARNING, "CommitToDevice for buffer at 0x%p failed (%ld) ", this, hrTmp);
}
#endif
}
#ifdef DEBUG
else
{
// again, not a catastrophic failure
DPF(DPFLVL_WARNING, "RequestWriteAccess failed for buffer at 0x%p failed with %ld", this, hrTmp );
}
#endif
}
}
}
else
{
MEMFREE(pwfxLocal);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetFrequency
*
* Description:
* Retrieves frequency for the given buffer.
*
* Arguments:
* LPDWORD [out]: receives the frequency.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetFrequency"
HRESULT CDirectSoundPrimaryBuffer::GetFrequency(LPDWORD pdwFrequency)
{
DPF_ENTER();
RPF(DPFLVL_ERROR, "Primary buffers don't support CTRLFREQUENCY");
DPF_LEAVE_HRESULT(DSERR_CONTROLUNAVAIL);
return DSERR_CONTROLUNAVAIL;
}
/***************************************************************************
*
* SetFrequency
*
* Description:
* Retrieves frequency for the given buffer.
*
* Arguments:
* DWORD [in]: frequency.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetFrequency"
HRESULT CDirectSoundPrimaryBuffer::SetFrequency(DWORD dwFrequency)
{
DPF_ENTER();
RPF(DPFLVL_ERROR, "Primary buffers don't support CTRLFREQUENCY");
DPF_LEAVE_HRESULT(DSERR_CONTROLUNAVAIL);
return DSERR_CONTROLUNAVAIL;
}
/***************************************************************************
*
* GetPan
*
* Description:
* Retrieves pan for the given buffer.
*
* Arguments:
* LPLONG [out]: receives the pan.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetPan"
HRESULT CDirectSoundPrimaryBuffer::GetPan(LPLONG plPan)
{
HRESULT hr = DS_OK;
DSVOLUMEPAN dsvp;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN");
hr = DSERR_CONTROLUNAVAIL;
}
// Ask the device for global attenuation and convert to pan
if(SUCCEEDED(hr))
{
hr = m_pDirectSound->m_pDevice->GetGlobalAttenuation(&dsvp);
}
if(SUCCEEDED(hr))
{
*plPan = dsvp.lPan;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetPan
*
* Description:
* Sets the pan for a given buffer.
*
* Arguments:
* LONG [in]: new pan.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetPan"
HRESULT CDirectSoundPrimaryBuffer::SetPan(LONG lPan)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN");
hr = DSERR_CONTROLUNAVAIL;
}
// Set device pan
if(SUCCEEDED(hr))
{
hr = m_pDirectSound->SetDevicePan(lPan);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetVolume
*
* Description:
* Retrieves volume for the given buffer.
*
* Arguments:
* LPLONG [out]: receives the volume.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetVolume"
HRESULT CDirectSoundPrimaryBuffer::GetVolume(LPLONG plVolume)
{
HRESULT hr = DS_OK;
DSVOLUMEPAN dsvp;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME");
hr = DSERR_CONTROLUNAVAIL;
}
// Ask the device for global attenuation and convert to volume
if(SUCCEEDED(hr))
{
hr = m_pDirectSound->m_pDevice->GetGlobalAttenuation(&dsvp);
}
if(SUCCEEDED(hr))
{
*plVolume = dsvp.lVolume;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetVolume
*
* Description:
* Sets the volume for a given buffer.
*
* Arguments:
* LONG [in]: new volume.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetVolume"
HRESULT CDirectSoundPrimaryBuffer::SetVolume(LONG lVolume)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME");
hr = DSERR_CONTROLUNAVAIL;
}
// Set device volume
if(SUCCEEDED(hr))
{
hr = m_pDirectSound->SetDeviceVolume(lVolume);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetNotificationPositions
*
* Description:
* Sets buffer notification positions.
*
* Arguments:
* DWORD [in]: DSBPOSITIONNOTIFY structure count.
* LPDSBPOSITIONNOTIFY [in]: offsets and events.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetNotificationPositions"
HRESULT CDirectSoundPrimaryBuffer::SetNotificationPositions(DWORD dwCount, LPCDSBPOSITIONNOTIFY paNotes)
{
DPF_ENTER();
RPF(DPFLVL_ERROR, "Primary buffers don't support CTRLPOSITIONNOTIFY");
DPF_LEAVE_HRESULT(DSERR_CONTROLUNAVAIL);
return DSERR_CONTROLUNAVAIL;
}
/***************************************************************************
*
* GetCurrentPosition
*
* Description:
* Gets the current play/write positions for the given buffer.
*
* Arguments:
* LPDWORD [out]: receives play cursor position.
* LPDWORD [out]: receives write cursor position.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetCurrentPosition"
HRESULT CDirectSoundPrimaryBuffer::GetCurrentPosition(LPDWORD pdwPlay, LPDWORD pdwWrite)
{
HRESULT hr = DS_OK;
DWORD dwPlay;
DWORD dwWrite;
DPF_ENTER();
// Check for BUFFERLOST
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
hr = DSERR_BUFFERLOST;
}
// Check access rights
if(SUCCEEDED(hr) && !m_fWritePrimary)
{
RPF(DPFLVL_ERROR, "Cooperative level is not WRITEPRIMARY");
hr = DSERR_PRIOLEVELNEEDED;
}
// We save the position to local variables so that the object we're
// calling into doesn't have to worry about whether one or both of
// the arguments are NULL.
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->GetCursorPosition(&dwPlay, &dwWrite);
}
// Block-align the positions
if(SUCCEEDED(hr))
{
dwPlay = BLOCKALIGN(dwPlay, m_dsbd.lpwfxFormat->nBlockAlign);
dwWrite = BLOCKALIGN(dwWrite, m_dsbd.lpwfxFormat->nBlockAlign);
}
// Apply app-hacks
if(SUCCEEDED(hr) && m_pDirectSound->m_ahAppHacks.lCursorPad)
{
dwPlay = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad);
dwWrite = PadCursor(dwWrite, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad);
}
if(SUCCEEDED(hr) && (m_pDirectSound->m_ahAppHacks.vdtReturnWritePos & m_pDirectSound->m_pDevice->m_vdtDeviceType))
{
dwPlay = dwWrite;
}
if(SUCCEEDED(hr) && m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.fEnable)
{
dwWrite = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.lCursorPad);
}
// Success
if(SUCCEEDED(hr) && pdwPlay)
{
*pdwPlay = dwPlay;
}
if(SUCCEEDED(hr) && pdwWrite)
{
*pdwWrite = dwWrite;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetCurrentPosition
*
* Description:
* Sets the current play position for a given buffer.
*
* Arguments:
* DWORD [in]: new play position.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetCurrentPosition"
HRESULT CDirectSoundPrimaryBuffer::SetCurrentPosition(DWORD dwPlayCursor)
{
DPF_ENTER();
RPF(DPFLVL_ERROR, "Primary buffers don't support SetCurrentPosition");
DPF_LEAVE_HRESULT(DSERR_INVALIDCALL);
return DSERR_INVALIDCALL;
}
/***************************************************************************
*
* GetStatus
*
* Description:
* Retrieves status for the given buffer.
*
* Arguments:
* LPDWORD [out]: receives the status.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetStatus"
HRESULT CDirectSoundPrimaryBuffer::GetStatus(LPDWORD pdwStatus)
{
HRESULT hr = DS_OK;
DWORD dwStatus;
DWORD dwState;
DPF_ENTER();
// Update the buffer status. If we're lost, that's the only state we
// care about
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
dwStatus = DSBSTATUS_BUFFERLOST;
}
else
{
// Get the current device buffer state
hr = m_pDeviceBuffer->GetState(&dwState);
if(SUCCEEDED(hr))
{
dwStatus = m_dwStatus;
UpdateBufferStatusFlags(dwState, &m_dwStatus);
}
// Fill in the buffer location
if(SUCCEEDED(hr))
{
m_dwStatus |= DSBCAPStoDSBSTATUS(m_dsbd.dwFlags);
}
if(SUCCEEDED(hr))
{
dwStatus = m_dwStatus;
}
}
// Mask off bits that shouldn't get back to the app
if(SUCCEEDED(hr))
{
dwStatus &= DSBSTATUS_USERMASK;
}
if(SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
dwStatus &= ~DSBSTATUS_LOCDEFERMASK;
}
if(SUCCEEDED(hr) && pdwStatus)
{
*pdwStatus = dwStatus;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Play
*
* Description:
* Starts the buffer playing.
*
* Arguments:
* DWORD [in]: priority.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Play"
HRESULT CDirectSoundPrimaryBuffer::Play(DWORD dwPriority, DWORD dwFlags)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Validate flags
if(dwFlags != DSBPLAY_LOOPING)
{
RPF(DPFLVL_ERROR, "The only valid flag for primary buffers is LOOPING, which must always be set");
hr = DSERR_INVALIDPARAM;
}
if(SUCCEEDED(hr) && dwPriority)
{
RPF(DPFLVL_ERROR, "Priority is not valid for primary buffers");
hr = DSERR_INVALIDPARAM;
}
// Check for BUFFERLOST
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST))
{
hr = DSERR_BUFFERLOST;
}
// Set the buffer state
if(SUCCEEDED(hr))
{
hr = SetBufferState(VAD_BUFFERSTATE_STARTED | VAD_BUFFERSTATE_LOOPING);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Stop
*
* Description:
* Stops playing the given buffer.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Stop"
HRESULT CDirectSoundPrimaryBuffer::Stop(void)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check for BUFFERLOST
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
hr = DSERR_BUFFERLOST;
}
// Set the buffer state
if(SUCCEEDED(hr))
{
hr = SetBufferState(VAD_BUFFERSTATE_STOPPED);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetBufferState
*
* Description:
* Sets the buffer play/stop state.
*
* Arguments:
* DWORD [in]: buffer state flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetBufferState"
HRESULT CDirectSoundPrimaryBuffer::SetBufferState(DWORD dwNewState)
{
DWORD dwOldState;
HRESULT hr;
DPF_ENTER();
if(m_fWritePrimary)
{
dwNewState &= ~VAD_BUFFERSTATE_WHENIDLE;
}
else
{
dwNewState |= VAD_BUFFERSTATE_WHENIDLE;
}
hr = m_pDeviceBuffer->GetState(&dwOldState);
if(SUCCEEDED(hr) && dwNewState != dwOldState)
{
hr = m_pDeviceBuffer->SetState(dwNewState);
}
if(SUCCEEDED(hr))
{
m_dwRestoreState = dwNewState;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Activate
*
* Description:
* Activates or deactivates the buffer object.
*
* Arguments:
* BOOL [in]: Activation state. TRUE to activate, FALSE to deactivate.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Activate"
HRESULT CDirectSoundPrimaryBuffer::Activate(BOOL fActive)
{
HRESULT hr;
DPF_ENTER();
// Apply cached properties. If we fail while doing this, hard luck,
// but there's nothing we can do about it. We should never return
// failure from Activate.
if(MAKEBOOL(m_dwStatus & DSBSTATUS_ACTIVE) != fActive)
{
if(fActive)
{
m_dwStatus |= DSBSTATUS_ACTIVE;
// Restore cached format
hr = m_pDirectSound->SetDeviceFormatExact(m_dsbd.lpwfxFormat);
if(FAILED(hr))
{
RPF(DPFLVL_WARNING, "Unable to restore cached primary buffer format");
}
// Restore primary buffer state
hr = SetBufferState(m_dwRestoreState);
if(FAILED(hr))
{
RPF(DPFLVL_WARNING, "Unable to restore cached primary buffer state");
}
}
else
{
m_dwStatus &= ~DSBSTATUS_ACTIVE;
}
}
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
/***************************************************************************
*
* SetPriority
*
* Description:
* Sets buffer priority.
*
* Arguments:
* DWORD [in]: new priority.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::SetPriority"
HRESULT CDirectSoundPrimaryBuffer::SetPriority(DWORD dwPriority)
{
const BOOL fCurrent = m_fWritePrimary;
const BOOL fNew = (DSSCL_WRITEPRIMARY == dwPriority);
HRESULT hr = DS_OK;
const DSBUFFERFOCUS bfFocus = g_pDsAdmin->GetBufferFocusState(this);
DPF_ENTER();
// Update our copy of the priority
m_fWritePrimary = fNew;
// If we're becoming WRITEPRIMARY but are out of focus, become immediately
// lost.
if (fNew && !fCurrent && bfFocus != DSBUFFERFOCUS_INFOCUS)
{
// Give up WRITEPRIMARY access
m_fWritePrimary = FALSE;
// Deactivate the buffer
Activate(FALSE);
// Flag the buffer as lost
m_dwStatus |= DSBSTATUS_BUFFERLOST;
hr = DSERR_OTHERAPPHASPRIO;
}
// Make sure the WRITEPRIMARY state has actually changed
if(SUCCEEDED(hr) && fNew != fCurrent)
{
// If we're becoming WRITEPRIMARY, we need to request primary
// access to the device.
if(fNew)
{
// Request write access
hr = m_pDeviceBuffer->RequestWriteAccess(TRUE);
if(SUCCEEDED(hr))
{
DPF(DPFLVL_INFO, "Buffer at 0x%p has become WRITEPRIMARY", this);
}
}
// Fill the buffer with silence. At this point, we MUST be WRITEPRIMARY.
if(SUCCEEDED(hr))
{
::FillSilence(m_pDeviceBuffer->m_pSysMemBuffer->GetPlayBuffer(), m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat->wBitsPerSample);
hr = m_pDeviceBuffer->CommitToDevice(0, m_pDeviceBuffer->m_pSysMemBuffer->GetSize());
}
// If we're leaving WRITEPRIMARY, we need to relinquish primary
// access to the device.
if(!fNew)
{
// Free any open locks on the buffer
m_pDeviceBuffer->OverrideLocks();
// Give up write access
hr = m_pDeviceBuffer->RequestWriteAccess(FALSE);
if(SUCCEEDED(hr))
{
DPF(DPFLVL_INFO, "Buffer at 0x%p is no longer WRITEPRIMARY", this);
}
}
// Reset the buffer state
if(SUCCEEDED(hr))
{
SetBufferState(VAD_BUFFERSTATE_STOPPED);
}
}
// If we're currently lost, but the cooperative level has changed to
// something other than WRITEPRIMARY, we'll go ahead and restore the
// buffer for the app. Only WRITEPRIMARY buffers can be lost.
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST) && !fNew)
{
m_dwStatus &= ~DSBSTATUS_BUFFERLOST;
}
// Recover from any errors
if(FAILED(hr))
{
m_fWritePrimary = fCurrent;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Lock
*
* Description:
* Locks the buffer memory to allow for writing.
*
* Arguments:
* DWORD [in]: offset, in bytes, from the start of the buffer to where
* the lock begins. This parameter is ignored if
* DSBLOCK_FROMWRITECURSOR is specified in the dwFlags
* parameter.
* DWORD [in]: size, in bytes, of the portion of the buffer to lock.
* Note that the sound buffer is conceptually circular.
* LPVOID * [out]: address for a pointer to contain the first block of
* the sound buffer to be locked.
* LPDWORD [out]: address for a variable to contain the number of bytes
* pointed to by the ppvAudioPtr1 parameter. If this
* value is less than the dwWriteBytes parameter,
* ppvAudioPtr2 will point to a second block of sound
* data.
* LPVOID * [out]: address for a pointer to contain the second block of
* the sound buffer to be locked. If the value of this
* parameter is NULL, the ppvAudioPtr1 parameter
* points to the entire locked portion of the sound
* buffer.
* LPDWORD [out]: address of a variable to contain the number of bytes
* pointed to by the ppvAudioPtr2 parameter. If
* ppvAudioPtr2 is NULL, this value will be 0.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Lock"
HRESULT CDirectSoundPrimaryBuffer::Lock(DWORD dwWriteCursor, DWORD dwWriteBytes, LPVOID *ppvAudioPtr1, LPDWORD pdwAudioBytes1, LPVOID *ppvAudioPtr2, LPDWORD pdwAudioBytes2, DWORD dwFlags)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check for BUFFERLOST
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
hr = DSERR_BUFFERLOST;
}
// Check access rights
if(SUCCEEDED(hr) && !m_fWritePrimary)
{
RPF(DPFLVL_ERROR, "Cooperative level is not WRITEPRIMARY");
hr = DSERR_PRIOLEVELNEEDED;
}
// Handle flags
if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_FROMWRITECURSOR))
{
hr = GetCurrentPosition(NULL, &dwWriteCursor);
}
if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_ENTIREBUFFER))
{
dwWriteBytes = m_dsbd.dwBufferBytes;
}
// Cursor validation
if(SUCCEEDED(hr) && dwWriteCursor >= m_dsbd.dwBufferBytes)
{
ASSERT(!(dwFlags & DSBLOCK_FROMWRITECURSOR));
RPF(DPFLVL_ERROR, "Write cursor past buffer end");
hr = DSERR_INVALIDPARAM;
}
if(SUCCEEDED(hr) && dwWriteBytes > m_dsbd.dwBufferBytes)
{
ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER));
RPF(DPFLVL_ERROR, "Lock size larger than buffer size");
hr = DSERR_INVALIDPARAM;
}
if(SUCCEEDED(hr) && !dwWriteBytes)
{
ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER));
RPF(DPFLVL_ERROR, "Lock size must be > 0");
hr = DSERR_INVALIDPARAM;
}
// Lock the device buffer
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->Lock(dwWriteCursor, dwWriteBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2);
}
m_bDataLocked = TRUE; // used to signal that app has written data (reset only required 1 per buffer creation)
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Unlock
*
* Description:
* Unlocks the given buffer.
*
* Arguments:
* LPVOID [in]: pointer to the first block.
* DWORD [in]: size of the first block.
* LPVOID [in]: pointer to the second block.
* DWORD [in]: size of the second block.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Unlock"
HRESULT CDirectSoundPrimaryBuffer::Unlock(LPVOID pvAudioPtr1, DWORD dwAudioBytes1, LPVOID pvAudioPtr2, DWORD dwAudioBytes2)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check for BUFFERLOST
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
hr = DSERR_BUFFERLOST;
}
// Check access rights
if(SUCCEEDED(hr) && !m_fWritePrimary)
{
RPF(DPFLVL_ERROR, "Cooperative level is not WRITEPRIMARY");
hr = DSERR_PRIOLEVELNEEDED;
}
// Unlock the device buffer. Because we fail the call when the buffer is
// lost (or out of focus), there's no need to notify the device buffer of
// any state change.
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->Unlock(pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Lose
*
* Description:
* Flags the buffer as lost.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Lose"
HRESULT CDirectSoundPrimaryBuffer::Lose(void)
{
DPF_ENTER();
// We can only be lost if we're WRITEPRIMARY
if(!(m_dwStatus & DSBSTATUS_BUFFERLOST) && m_fWritePrimary)
{
// Stop the buffer. All lost buffers are stopped by definition.
SetBufferState(VAD_BUFFERSTATE_STOPPED);
// Give up WRITEPRIMARY access
SetPriority(DSSCL_NONE);
// Deactivate the buffer
Activate(FALSE);
// Flag the buffer as lost
m_dwStatus |= DSBSTATUS_BUFFERLOST;
}
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
/***************************************************************************
*
* Restore
*
* Description:
* Attempts to restore a lost bufer.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::Restore"
HRESULT CDirectSoundPrimaryBuffer::Restore(void)
{
HRESULT hr = DS_OK;
DPF_ENTER();
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
// Are we still lost?
if(DSBUFFERFOCUS_LOST == g_pDsAdmin->GetBufferFocusState(this))
{
hr = DSERR_BUFFERLOST;
}
// Remove the lost flag
if(SUCCEEDED(hr))
{
m_dwStatus &= ~DSBSTATUS_BUFFERLOST;
}
// Reset the focus priority
if(SUCCEEDED(hr))
{
hr = SetPriority(m_pDirectSound->m_dsclCooperativeLevel.dwPriority);
}
// Clean up
if(FAILED(hr))
{
m_dwStatus |= DSBSTATUS_BUFFERLOST;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* CDirectSoundSecondaryBuffer
*
* Description:
* DirectSound secondary buffer object constructor.
*
* Arguments:
* CDirectSound * [in]: pointer to the parent object.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::CDirectSoundSecondaryBuffer"
CDirectSoundSecondaryBuffer::CDirectSoundSecondaryBuffer(CDirectSound *pDirectSound)
: CDirectSoundBuffer(pDirectSound)
{
DPF_ENTER();
DPF_CONSTRUCT(CDirectSoundSecondaryBuffer);
// Initialize/check defaults
ASSERT(m_pImpDirectSoundBuffer == NULL);
ASSERT(m_pImpDirectSoundNotify == NULL);
ASSERT(m_pOwningSink == NULL);
ASSERT(m_pDeviceBuffer == NULL);
ASSERT(m_p3dBuffer == NULL);
ASSERT(m_pPropertySet == NULL);
ASSERT(m_fxChain == NULL);
ASSERT(m_dwPriority == 0);
ASSERT(m_dwVmPriority == 0);
ASSERT(m_fMute == FALSE);
#ifdef FUTURE_MULTIPAN_SUPPORT
ASSERT(m_dwChannelCount == 0);
ASSERT(m_pdwChannels == NULL);
ASSERT(m_plChannelVolumes == NULL);
#endif
ASSERT(m_guidBufferID == GUID_NULL);
ASSERT(m_dwAHLastGetPosTime == 0);
ASSERT(m_dwAHCachedPlayPos == 0);
ASSERT(m_dwAHCachedWritePos == 0);
m_fCanStealResources = TRUE;
m_hrInit = DSERR_UNINITIALIZED;
m_hrPlay = DS_OK;
m_playState = Stopped;
m_dwSliceBegin = MAX_DWORD;
m_dwSliceEnd = MAX_DWORD;
#ifdef ENABLE_PERFLOG
// Initialize performance state if logging is enabled
m_pPerfState = NULL;
if (PerflogTracingEnabled())
{
m_pPerfState = NEW(BufferPerfState(this));
// We don't mind if this allocation fails
}
#endif
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* ~CDirectSoundSecondaryBuffer
*
* Description:
* DirectSound secondary buffer object destructor.
*
* Arguments:
* (void)
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::~CDirectSoundSecondaryBuffer"
CDirectSoundSecondaryBuffer::~CDirectSoundSecondaryBuffer(void)
{
HRESULT hr;
DPF_ENTER();
DPF_DESTRUCT(CDirectSoundBuffer);
// If we're a MIXIN buffer, inform all our senders that we're going
// away, and unregister with the streaming thread
if ((m_dsbd.dwFlags & DSBCAPS_MIXIN) && SUCCEEDED(m_hrInit))
{
CNode<CDirectSoundSecondaryBuffer*>* pDsbNode;
for (pDsbNode = m_pDirectSound->m_lstSecondaryBuffers.GetListHead(); pDsbNode; pDsbNode = pDsbNode->m_pNext)
if (pDsbNode->m_data->HasFX())
pDsbNode->m_data->m_fxChain->NotifyRelease(this);
m_pStreamingThread->UnregisterMixBuffer(this);
}
// If we're a SINKIN buffer, unregister with our owning sink
if (m_pOwningSink)
{
hr = m_pOwningSink->RemoveBuffer(this);
ASSERT(SUCCEEDED(hr));
RELEASE(m_pOwningSink);
}
// Release our FX chain, if we have one
RELEASE(m_fxChain);
// Make sure the buffer is stopped
if(m_pDeviceBuffer)
{
hr = SetBufferState(VAD_BUFFERSTATE_STOPPED);
ASSERT(SUCCEEDED(hr) || hr == DSERR_NODRIVER);
}
// Unregister with the parent object
m_pDirectSound->m_lstSecondaryBuffers.RemoveDataFromList(this);
// Free all interfaces
DELETE(m_pImpDirectSoundNotify);
DELETE(m_pImpDirectSoundBuffer);
// Free owned objects
ABSOLUTE_RELEASE(m_p3dBuffer);
ABSOLUTE_RELEASE(m_pPropertySet);
// Release the device buffer
RELEASE(m_pDeviceBuffer);
// Clean up memory
#ifdef FUTURE_MULTIPAN_SUPPORT
MEMFREE(m_pdwChannels);
MEMFREE(m_plChannelVolumes);
#endif
#ifdef ENABLE_PERFLOG
DELETE(m_pPerfState);
#endif
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* Initialize
*
* Description:
* Initializes a buffer object. If this function fails, the object
* should be immediately deleted.
*
* Arguments:
* LPDSBUFFERDESC [in]: buffer description.
* CDirectSoundBuffer * [in]: source buffer to duplicate from, or NULL
* to create a new buffer object.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Initialize"
HRESULT CDirectSoundSecondaryBuffer::Initialize(LPCDSBUFFERDESC pDesc, CDirectSoundSecondaryBuffer *pSource)
{
#ifdef DEBUG
const ULONG ulKsIoctlCount = g_ulKsIoctlCount;
#endif // DEBUG
DSBUFFERFOCUS bfFocus;
VADRBUFFERCAPS vrbc;
HRESULT hr;
DPF_ENTER();
ASSERT(IsInit() == DSERR_UNINITIALIZED);
ASSERT(LXOR(pSource, pDesc));
if(pDesc)
{
DPF(DPFLVL_MOREINFO, "dwFlags: 0x%8.8lX", pDesc->dwFlags);
DPF(DPFLVL_MOREINFO, "dwBufferBytes: %lu", pDesc->dwBufferBytes);
DPF(DPFLVL_MOREINFO, "dwReserved: %lu", pDesc->dwReserved);
if(pDesc->lpwfxFormat)
{
DPF(DPFLVL_MOREINFO, "lpwfxFormat->wFormatTag: %u", pDesc->lpwfxFormat->wFormatTag);
DPF(DPFLVL_MOREINFO, "lpwfxFormat->nChannels: %u", pDesc->lpwfxFormat->nChannels);
DPF(DPFLVL_MOREINFO, "lpwfxFormat->nSamplesPerSec: %lu", pDesc->lpwfxFormat->nSamplesPerSec);
DPF(DPFLVL_MOREINFO, "lpwfxFormat->nAvgBytesPerSec: %lu", pDesc->lpwfxFormat->nAvgBytesPerSec);
DPF(DPFLVL_MOREINFO, "lpwfxFormat->nBlockAlign: %u", pDesc->lpwfxFormat->nBlockAlign);
DPF(DPFLVL_MOREINFO, "lpwfxFormat->wBitsPerSample: %u", pDesc->lpwfxFormat->wBitsPerSample);
if(WAVE_FORMAT_PCM != pDesc->lpwfxFormat->wFormatTag)
{
DPF(DPFLVL_MOREINFO, "lpwfxFormat->cbSize: %u", pDesc->lpwfxFormat->cbSize);
}
}
DPF(DPFLVL_MOREINFO, "guid3DAlgorithm: " DPF_GUID_STRING, DPF_GUID_VAL(pDesc->guid3DAlgorithm));
}
// Initialize the buffer
hr = InitializeEmpty(pDesc, pSource);
// Register with the parent object
if(SUCCEEDED(hr))
{
hr = HRFROMP(m_pDirectSound->m_lstSecondaryBuffers.AddNodeToList(this));
}
// Set default properties
if(SUCCEEDED(hr))
{
if(pSource && (m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME) && DSBVOLUME_MAX != pSource->m_lVolume)
{
SetVolume(pSource->m_lVolume);
}
else
{
m_lVolume = DSBVOLUME_MAX;
}
}
if(SUCCEEDED(hr))
{
if(pSource && (m_dsbd.dwFlags & DSBCAPS_CTRLPAN) && DSBPAN_CENTER != pSource->m_lPan)
{
SetPan(pSource->m_lPan);
}
else
{
m_lPan = DSBPAN_CENTER;
}
}
if(SUCCEEDED(hr))
{
if(pSource && (m_dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY) && m_dsbd.lpwfxFormat->nSamplesPerSec != pSource->m_dwFrequency)
{
SetFrequency(pSource->m_dwFrequency);
}
else
{
m_dwFrequency = m_dsbd.lpwfxFormat->nSamplesPerSec;
}
}
// Attempt to create the property set object
if(SUCCEEDED(hr))
{
m_pPropertySet = NEW(CDirectSoundSecondaryBufferPropertySet(this));
hr = HRFROMP(m_pPropertySet);
if(SUCCEEDED(hr))
{
hr = m_pPropertySet->Initialize();
}
}
// Attempt to create the 3D buffer
if(SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_CTRL3D))
{
m_p3dBuffer = NEW(CDirectSound3dBuffer(this));
hr = HRFROMP(m_p3dBuffer);
if(SUCCEEDED(hr))
{
hr = m_p3dBuffer->Initialize(m_dsbd.guid3DAlgorithm, m_dsbd.dwFlags, m_dwFrequency, m_pDirectSound->m_pPrimaryBuffer->m_p3dListener, pSource ? pSource->m_p3dBuffer : NULL);
}
}
// Handle any possible resource acquisitions
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->GetCaps(&vrbc);
}
// Manbug 36422: CEmSecondaryRenderWaveBuffer objects can return LOCSOFTWARE|LOCDEFER,
// in which case we incorrectly acquired resources here for deferred emulated buffers.
// Hence the "&& !(vrbc.dwFlags & DSBCAPS_LOCDEFER)" below.
if(SUCCEEDED(hr) && (vrbc.dwFlags & DSBCAPS_LOCMASK) && !(vrbc.dwFlags & DSBCAPS_LOCDEFER))
{
hr = HandleResourceAcquisition(vrbc.dwFlags & DSBCAPS_LOCMASK);
}
// Register the interfaces with the interface manager
if(SUCCEEDED(hr))
{
hr = CreateAndRegisterInterface(this, IID_IDirectSoundBuffer, this, &m_pImpDirectSoundBuffer);
}
if(SUCCEEDED(hr) && GetDsVersion() >= DSVERSION_DX8)
{
hr = RegisterInterface(IID_IDirectSoundBuffer8, m_pImpDirectSoundBuffer, m_pImpDirectSoundBuffer);
}
if(SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY))
{
hr = CreateAndRegisterInterface(this, IID_IDirectSoundNotify, this, &m_pImpDirectSoundNotify);
}
// Initialize focus state
if(SUCCEEDED(hr))
{
bfFocus = g_pDsAdmin->GetBufferFocusState(this);
switch(bfFocus)
{
case DSBUFFERFOCUS_INFOCUS:
hr = Activate(TRUE);
break;
case DSBUFFERFOCUS_OUTOFFOCUS:
hr = Activate(FALSE);
break;
case DSBUFFERFOCUS_LOST:
hr = Lose();
break;
}
}
// If this is a MIXIN buffer, register it with the streaming thread
if (SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_MIXIN))
{
m_pStreamingThread = GetStreamingThread();
hr = HRFROMP(m_pStreamingThread);
if (SUCCEEDED(hr))
{
hr = m_pStreamingThread->RegisterMixBuffer(this);
}
}
// Success
if(SUCCEEDED(hr))
{
#ifdef DEBUG
if(IS_KS_VAD(m_pDirectSound->m_pDevice->m_vdtDeviceType))
{
DPF(DPFLVL_MOREINFO, "%s used %lu IOCTLs", TEXT(DPF_FNAME), g_ulKsIoctlCount - ulKsIoctlCount);
}
#endif // DEBUG
m_hrInit = DS_OK;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* InitializeEmpty
*
* Description:
* Initializes a buffer object.
*
* Arguments:
* LPDSBUFFERDESC [in]: buffer description.
* CDirectSoundBuffer * [in]: source buffer to duplicate from, or NULL
* to create a new buffer object.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::InitializeEmpty"
HRESULT CDirectSoundSecondaryBuffer::InitializeEmpty(LPCDSBUFFERDESC pDesc, CDirectSoundSecondaryBuffer *pSource)
{
BOOL fRealDuplicate = FALSE;
VADRBUFFERDESC vrbd;
HRESULT hr;
DPF_ENTER();
// Save buffer description
if(pSource)
{
m_dwOriginalFlags = pSource->m_dwOriginalFlags;
hr = CopyDsBufferDesc(&pSource->m_dsbd, &m_dsbd);
// We're going to reset the flags back to those originally passed to
// CreateSoundBuffer so that the duplicate buffer is created with
// the same *requested* capabilities as the original.
// COMPATCOMPAT: one side effect of doing this is that if the source buffer
// is in hardware, but no location flags were specified when creating it,
// any number of its duplicates may potentially live in software. This
// is new behavior as of version 5.0a.
if(SUCCEEDED(hr))
{
m_dsbd.dwFlags = m_dwOriginalFlags;
}
}
else
{
m_dwOriginalFlags = pDesc->dwFlags;
hr = CopyDsBufferDesc(pDesc, &m_dsbd);
}
// Fill in any missing pieces
if(SUCCEEDED(hr) && !pSource)
{
m_dsbd.dwBufferBytes = GetAlignedBufferSize(m_dsbd.lpwfxFormat, m_dsbd.dwBufferBytes);
}
// Include legacy Voice Manager stuff
if(SUCCEEDED(hr) && DSPROPERTY_VMANAGER_MODE_DEFAULT != m_pDirectSound->m_vmmMode)
{
m_dsbd.dwFlags |= DSBCAPS_LOCDEFER;
}
// Attempt to duplicate the device buffer
if(SUCCEEDED(hr) && pSource)
{
hr = pSource->m_pDeviceBuffer->Duplicate(&m_pDeviceBuffer);
// If we failed to duplicate the buffer, and the source buffer's
// original flags don't specify a location, fall back on software.
fRealDuplicate = SUCCEEDED(hr);
if(FAILED(hr) && !(pSource->m_dwOriginalFlags & DSBCAPS_LOCHARDWARE))
{
hr = DS_OK;
}
}
// Attempt to create the device buffer
if(SUCCEEDED(hr) && !m_pDeviceBuffer)
{
vrbd.dwFlags = m_dsbd.dwFlags;
vrbd.dwBufferBytes = m_dsbd.dwBufferBytes;
vrbd.pwfxFormat = m_dsbd.lpwfxFormat;
vrbd.guid3dAlgorithm = m_dsbd.guid3DAlgorithm;
hr = m_pDirectSound->m_pDevice->CreateSecondaryBuffer(&vrbd, m_pDirectSound, &m_pDeviceBuffer);
}
// Initialize the buffer data
if(SUCCEEDED(hr))
{
if(pSource)
{
if(!fRealDuplicate)
{
ASSERT(m_pDeviceBuffer->m_pSysMemBuffer->GetSize() == m_dsbd.dwBufferBytes);
ASSERT(pSource->m_pDeviceBuffer->m_pSysMemBuffer->GetSize() == m_dsbd.dwBufferBytes);
CopyMemory(GetWriteBuffer(), pSource->GetWriteBuffer(), m_dsbd.dwBufferBytes);
}
}
else if(GetBufferType()) // If true, buffer is MIXIN or SINKIN (FIXME - does this simplify the sink?)
{
ClearWriteBuffer();
}
else
{
#ifdef RDEBUG
// Write some ugly noise into the buffer to catch remiss apps
::FillNoise(GetWriteBuffer(), m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat->wBitsPerSample);
#else // RDEBUG
if(GetDsVersion() < DSVERSION_DX8)
{
// For apps written for DirectX 8 or later, we decided not to
// waste time initializing all secondary buffers with silence.
// They'll still be zeroed out by our memory allocator, though ;-)
ClearWriteBuffer();
}
#endif // RDEBUG
}
if(!pSource || !fRealDuplicate)
{
hr = CommitToDevice(0, m_dsbd.dwBufferBytes);
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* AttemptResourceAcquisition
*
* Description:
* Acquires hardware resources.
*
* Arguments:
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::AttemptResourceAcquisition"
HRESULT CDirectSoundSecondaryBuffer::AttemptResourceAcquisition(DWORD dwFlags)
{
HRESULT hr = DSERR_INVALIDPARAM;
CList<CDirectSoundSecondaryBuffer *> lstBuffers;
CNode<CDirectSoundSecondaryBuffer *> * pNode;
HRESULT hrTemp;
DPF_ENTER();
ASSERT(m_pDeviceBuffer);
if (m_dwStatus & DSBSTATUS_RESOURCESACQUIRED)
{
hr = DS_OK;
}
else
{
// Include legacy Voice Manager stuff
if(DSPROPERTY_VMANAGER_MODE_DEFAULT != m_pDirectSound->m_vmmMode)
{
ASSERT(m_dsbd.dwFlags & DSBCAPS_LOCDEFER);
ASSERT(!(dwFlags & DSBPLAY_LOCDEFERMASK));
dwFlags &= ~DSBPLAY_LOCDEFERMASK;
dwFlags |= DSBCAPStoDSBPLAY(m_dsbd.dwFlags);
switch(m_pDirectSound->m_vmmMode)
{
case DSPROPERTY_VMANAGER_MODE_AUTO:
dwFlags |= DSBPLAY_TERMINATEBY_TIME;
break;
case DSPROPERTY_VMANAGER_MODE_USER:
dwFlags |= DSBPLAY_TERMINATEBY_PRIORITY;
break;
}
}
// Try to acquire resources. If any of the TERMINATEBY flags were specified,
// we'll need to try to explicitly acquire hardware resources, then attempt
// to steal, then fall back on software.
if(!(dwFlags & DSBPLAY_LOCSOFTWARE))
{
hr = AcquireResources(DSBCAPS_LOCHARDWARE);
if(FAILED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_MASK))
{
hrTemp = GetResourceTheftCandidates(dwFlags & DSBPLAY_TERMINATEBY_MASK, &lstBuffers);
if(SUCCEEDED(hrTemp))
{
if(pNode = lstBuffers.GetListHead())
hr = StealResources(pNode->m_data);
}
else
{
hr = hrTemp;
}
}
}
if(FAILED(hr) && !(dwFlags & DSBPLAY_LOCHARDWARE))
{
hr = AcquireResources(DSBCAPS_LOCSOFTWARE);
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* AcquireResources
*
* Description:
* Acquires hardware resources.
*
* Arguments:
* DWORD [in]: buffer location flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::AcquireResources"
HRESULT CDirectSoundSecondaryBuffer::AcquireResources(DWORD dwFlags)
{
VADRBUFFERCAPS vrbc;
HRESULT hr;
DPF_ENTER();
ASSERT(m_pDeviceBuffer);
ASSERT(!(m_dwStatus & DSBSTATUS_RESOURCESACQUIRED));
hr = m_pDeviceBuffer->GetCaps(&vrbc);
if(SUCCEEDED(hr))
{
if(!(vrbc.dwFlags & DSBCAPS_LOCMASK))
{
// Try to acquire the device buffer
hr = m_pDeviceBuffer->AcquireResources(dwFlags);
}
else if((dwFlags & DSBCAPS_LOCMASK) != (vrbc.dwFlags & DSBCAPS_LOCMASK))
{
hr = DSERR_INVALIDCALL;
}
}
if(SUCCEEDED(hr))
{
DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has acquired resources at 0x%p", this, m_pDeviceBuffer);
hr = CommitToDevice(0, m_dsbd.dwBufferBytes);
// Handle the resource acquisition
if(SUCCEEDED(hr))
{
hr = HandleResourceAcquisition(vrbc.dwFlags & DSBCAPS_LOCMASK);
}
if (FAILED(hr))
{
// Free any resources acquired so far
HRESULT hrTemp = FreeResources(FALSE);
ASSERT(SUCCEEDED(hrTemp)); // Not much we can do if this fails
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* StealResources
*
* Description:
* Steals hardware resources from another buffer.
*
* Arguments:
* CDirectSoundSecondaryBuffer * [in]: buffer to steal from.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::StealResources"
HRESULT CDirectSoundSecondaryBuffer::StealResources(CDirectSoundSecondaryBuffer *pSource)
{
VADRBUFFERCAPS vrbc;
HRESULT hrTemp;
HRESULT hr;
DPF_ENTER();
ASSERT(m_pDeviceBuffer);
ASSERT(!(m_dwStatus & DSBSTATUS_RESOURCESACQUIRED));
DPF(DPFLVL_INFO, "Stealing resources from buffer at 0x%p", pSource);
ASSERT(pSource->m_dwStatus & DSBSTATUS_RESOURCESACQUIRED);
// Get the buffer location
hr = pSource->m_pDeviceBuffer->GetCaps(&vrbc);
if(SUCCEEDED(hr))
{
ASSERT(vrbc.dwFlags & DSBCAPS_LOCHARDWARE);
}
// Steal hardware resources
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->StealResources(pSource->m_pDeviceBuffer);
}
if(SUCCEEDED(hr))
{
// Free the source buffer's resources (since they're now our resources).
hr = pSource->FreeResources(TRUE);
if(SUCCEEDED(hr))
{
hr = CommitToDevice(0, m_dsbd.dwBufferBytes);
}
// Handle the resource acquisition
if(SUCCEEDED(hr))
{
hr = HandleResourceAcquisition(vrbc.dwFlags & DSBCAPS_LOCMASK);
}
}
else if(DSERR_UNSUPPORTED == hr)
{
// The device buffer doesn't support resource theft. Free the
// source buffer's resources and try to acquire our own.
hr = pSource->FreeResources(TRUE);
if(SUCCEEDED(hr))
{
hr = AcquireResources(DSBCAPS_LOCHARDWARE);
// Try to reacquire the source buffer's resources
if(FAILED(hr))
{
hrTemp = pSource->AcquireResources(DSBCAPS_LOCHARDWARE);
if(FAILED(hrTemp))
{
RPF(DPFLVL_ERROR, "Unable to reacquire hardware resources!");
}
}
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetResourceTheftCandidates
*
* Description:
* Finds objects that are available to have their resources stolen.
*
* Arguments:
* CList * [out]: destination list.
* DWORD [in]: TERMINATEBY flags. If none are specified, all
* compatible buffers are added to the list.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetResourceTheftCandidates"
HRESULT CDirectSoundSecondaryBuffer::GetResourceTheftCandidates(DWORD dwFlags, CList<CDirectSoundSecondaryBuffer *> *plstDest)
{
HRESULT hr = DS_OK;
CNode<CDirectSoundSecondaryBuffer *> * pNode;
CNode<CDirectSoundSecondaryBuffer *> * pNext;
CDirectSoundSecondaryBuffer * pTimeBuffer;
DWORD dwStatus;
DWORD dwMinPriority;
DWORD dwPriority;
DWORD cbMinRemain;
DWORD cbRemain;
COMPAREBUFFER cmp[2];
DPF_ENTER();
ASSERT(m_pDeviceBuffer);
// First, find all compatible buffers
for(pNode = m_pDirectSound->m_lstSecondaryBuffers.GetListHead(); pNode; pNode = pNode->m_pNext)
{
// We never want to look at ourselves. It's just sick.
if(this == pNode->m_data)
{
continue;
}
// We can only steal from LOCDEFER buffers
if(!(pNode->m_data->m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
continue;
}
// This flag prevents us from stealing resources from buffers that have
// just called UserAcquireResources() and haven't called Play() yet
if(!pNode->m_data->m_fCanStealResources)
{
continue;
}
// Make sure the object actually has some hardware resources
hr = pNode->m_data->GetStatus(&dwStatus);
if(FAILED(hr))
{
break;
}
if(!(dwStatus & DSBSTATUS_LOCHARDWARE))
{
continue;
}
// Compare the buffer properties
cmp[0].dwFlags = m_dsbd.dwFlags;
cmp[0].pwfxFormat = m_dsbd.lpwfxFormat;
cmp[0].guid3dAlgorithm = m_dsbd.guid3DAlgorithm;
cmp[1].dwFlags = pNode->m_data->m_dsbd.dwFlags;
cmp[1].pwfxFormat = pNode->m_data->m_dsbd.lpwfxFormat;
cmp[1].guid3dAlgorithm = pNode->m_data->m_dsbd.guid3DAlgorithm;
if(!CompareBufferProperties(&cmp[0], &cmp[1]))
{
continue;
}
hr = HRFROMP(plstDest->AddNodeToList(pNode->m_data));
if (FAILED(hr))
{
break;
}
}
if(SUCCEEDED(hr))
{
DPF(DPFLVL_MOREINFO, "Found %lu compatible buffers", plstDest->GetNodeCount());
}
// Remove all buffers that are > the lowest priority
if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_PRIORITY))
{
dwMinPriority = GetBufferPriority();
for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext)
{
dwPriority = pNode->m_data->GetBufferPriority();
if(dwPriority < dwMinPriority)
{
dwMinPriority = dwPriority;
}
}
pNode = plstDest->GetListHead();
while(pNode)
{
pNext = pNode->m_pNext;
dwPriority = pNode->m_data->GetBufferPriority();
if(dwPriority > dwMinPriority)
{
plstDest->RemoveNodeFromList(pNode);
}
pNode = pNext;
}
#ifdef DEBUG
DPF(DPFLVL_MOREINFO, "%lu buffers passed the priority test", plstDest->GetNodeCount());
for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext)
{
DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has priority %lu", pNode->m_data, pNode->m_data->GetBufferPriority());
}
#endif // DEBUG
}
// Remove any buffers that aren't at max distance
if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_DISTANCE))
{
pNode = plstDest->GetListHead();
while(pNode)
{
pNext = pNode->m_pNext;
if(!pNode->m_data->m_p3dBuffer || !pNode->m_data->m_p3dBuffer->m_pWrapper3dObject->IsAtMaxDistance())
{
plstDest->RemoveNodeFromList(pNode);
}
pNode = pNext;
}
#ifdef DEBUG
DPF(DPFLVL_MOREINFO, "%lu buffers passed the distance test", plstDest->GetNodeCount());
for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext)
{
DPF(DPFLVL_MOREINFO, "Buffer at 0x%p is at max distance", pNode->m_data);
}
#endif // DEBUG
}
// Find the buffer with the least amount of time remaining
if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_TERMINATEBY_TIME))
{
cbMinRemain = MAX_DWORD;
pTimeBuffer = NULL;
for(pNode = plstDest->GetListHead(); pNode; pNode = pNode->m_pNext)
{
hr = pNode->m_data->GetPlayTimeRemaining(&cbRemain);
if(FAILED(hr))
{
break;
}
DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has %lu bytes remaining", pNode->m_data, cbRemain);
if(cbRemain < cbMinRemain)
{
cbMinRemain = cbRemain;
pTimeBuffer = pNode->m_data;
}
}
if(SUCCEEDED(hr))
{
plstDest->RemoveAllNodesFromList();
if(pTimeBuffer)
{
hr = HRFROMP(plstDest->AddNodeToList(pTimeBuffer));
}
DPF(DPFLVL_MOREINFO, "%lu buffers passed the time test", plstDest->GetNodeCount());
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetPlayTimeRemaining
*
* Description:
* Gets the amount of time the buffer has remaining before stopping.
*
* Arguments:
* LPDWORD [out]: receives time (in bytes).
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetPlayTimeRemaining"
HRESULT CDirectSoundSecondaryBuffer::GetPlayTimeRemaining(LPDWORD pdwRemain)
{
DWORD dwRemain = MAX_DWORD;
HRESULT hr = DS_OK;
DWORD dwPlay;
DPF_ENTER();
if(!(m_dwStatus & DSBSTATUS_LOOPING))
{
hr = GetCurrentPosition(&dwPlay, NULL);
if(SUCCEEDED(hr))
{
dwRemain = m_dsbd.dwBufferBytes - dwPlay;
}
}
if(SUCCEEDED(hr))
{
*pdwRemain = dwRemain;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* FreeResources
*
* Description:
* Frees hardware resources.
*
* Arguments:
* BOOL [in]: TRUE if the buffer has been terminated as a result of
* resources being stolen.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::FreeResources"
HRESULT CDirectSoundSecondaryBuffer::FreeResources(BOOL fTerminate)
{
HRESULT hr;
DPF_ENTER();
ASSERT(m_pDeviceBuffer);
// Make sure the buffer is stopped
hr = SetBufferState(VAD_BUFFERSTATE_STOPPED);
// Free owned objects' resources
if(SUCCEEDED(hr) && m_p3dBuffer)
{
hr = m_p3dBuffer->FreeResources();
}
if(SUCCEEDED(hr) && m_pPropertySet)
{
hr = m_pPropertySet->FreeResources();
}
// Free the device buffer's resources
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->FreeResources();
}
// Resources have been freed
if(SUCCEEDED(hr))
{
DPF(DPFLVL_MOREINFO, "Buffer at 0x%p has freed its resources", this);
m_dwStatus &= ~DSBSTATUS_RESOURCESACQUIRED;
}
// If resources were freed as a result of a termination, update
// the status.
if(SUCCEEDED(hr) && fTerminate)
{
m_dwStatus |= DSBSTATUS_TERMINATED;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* HandleResourceAcquisition
*
* Description:
* Handles acquisition of hardware resources.
*
* Arguments:
* DWORD [in]: location flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::HandleResourceAcquisition"
HRESULT CDirectSoundSecondaryBuffer::HandleResourceAcquisition(DWORD dwFlags)
{
HRESULT hr = S_OK;
DPF_ENTER();
ASSERT(m_pDeviceBuffer);
// Acquire 3D resources
if(SUCCEEDED(hr) && m_p3dBuffer)
{
hr = m_p3dBuffer->AcquireResources(m_pDeviceBuffer);
}
// Acquire property set resources. It's OK if this fails.
if(SUCCEEDED(hr) && m_pPropertySet)
{
m_pPropertySet->AcquireResources(m_pDeviceBuffer);
}
// Acquire effect handling resources if necessary
if(SUCCEEDED(hr) && HasFX())
{
hr = m_fxChain->AcquireFxResources();
}
// Resources have been acquired
if(SUCCEEDED(hr))
{
m_dwStatus |= DSBSTATUS_RESOURCESACQUIRED;
}
// If the buffer was created *without* LOCDEFER, the caps must reflect
// the location. If the buffer was create *with* LOCDEFER, the caps
// will never reflect anything other than that; call GetStatus instead.
if(SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
m_dsbd.dwFlags |= dwFlags & DSBCAPS_LOCMASK;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetCaps
*
* Description:
* Queries capabilities for the buffer.
*
* Arguments:
* LPDSBCAPS [out]: receives caps.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetCaps"
HRESULT CDirectSoundSecondaryBuffer::GetCaps(LPDSBCAPS pDsbCaps)
{
DPF_ENTER();
ASSERT(sizeof(DSBCAPS) == pDsbCaps->dwSize);
if(m_dsbd.dwFlags & DSBCAPS_LOCDEFER)
{
ASSERT(!(m_dsbd.dwFlags & DSBCAPS_LOCMASK));
}
else
{
ASSERT(LXOR(m_dsbd.dwFlags & DSBCAPS_LOCSOFTWARE, m_dsbd.dwFlags & DSBCAPS_LOCHARDWARE));
}
pDsbCaps->dwFlags = m_dsbd.dwFlags & DSBCAPS_VALIDFLAGS; // Remove any special internal flags (e.g. DSBCAPS_SINKIN)
pDsbCaps->dwBufferBytes = GetBufferType() ? 0 : m_dsbd.dwBufferBytes; // Shouldn't report internal size of sink/MIXIN buffers
pDsbCaps->dwUnlockTransferRate = 0;
pDsbCaps->dwPlayCpuOverhead = 0;
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
/***************************************************************************
*
* GetFormat
*
* Description:
* Retrieves the format for the given buffer.
*
* Arguments:
* LPWAVEFORMATEX [out]: receives the format.
* LPDWORD [in/out]: size of the format structure. On entry, this
* must be initialized to the size of the structure.
* On exit, this will be filled with the size that
* was required.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetFormat"
HRESULT CDirectSoundSecondaryBuffer::GetFormat(LPWAVEFORMATEX pwfxFormat, LPDWORD pdwSize)
{
HRESULT hr = DS_OK;
DPF_ENTER();
hr = CopyWfxApi(m_dsbd.lpwfxFormat, pwfxFormat, pdwSize);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetFormat
*
* Description:
* Sets the format for a given buffer.
*
* Arguments:
* LPWAVEFORMATEX [in]: new format.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFormat"
HRESULT CDirectSoundSecondaryBuffer::SetFormat(LPCWAVEFORMATEX pwfxFormat)
{
DPF_ENTER();
RPF(DPFLVL_ERROR, "Secondary buffers don't support SetFormat");
DPF_LEAVE_HRESULT(DSERR_INVALIDCALL);
return DSERR_INVALIDCALL;
}
/***************************************************************************
*
* GetFrequency
*
* Description:
* Retrieves frequency for the given buffer.
*
* Arguments:
* LPDWORD [out]: receives the frequency.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPrimaryBuffer::GetFrequency"
HRESULT CDirectSoundSecondaryBuffer::GetFrequency(LPDWORD pdwFrequency)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLFREQUENCY");
hr = DSERR_CONTROLUNAVAIL;
}
if(SUCCEEDED(hr))
{
*pdwFrequency = m_dwFrequency;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetFrequency
*
* Description:
* Sets the frequency for the given buffer.
*
* Arguments:
* DWORD [in]: frequency.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFrequency"
HRESULT CDirectSoundSecondaryBuffer::SetFrequency(DWORD dwFrequency)
{
BOOL fContinue = TRUE;
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLFREQUENCY");
hr = DSERR_CONTROLUNAVAIL;
}
// Handle default frequency
if(SUCCEEDED(hr) && DSBFREQUENCY_ORIGINAL == dwFrequency)
{
dwFrequency = m_dsbd.lpwfxFormat->nSamplesPerSec;
}
// Validate the frequency
if(SUCCEEDED(hr) && (dwFrequency < DSBFREQUENCY_MIN || dwFrequency > DSBFREQUENCY_MAX))
{
RPF(DPFLVL_ERROR, "Specified invalid frequency %lu (valid range is %lu to %lu)", dwFrequency, DSBFREQUENCY_MIN, DSBFREQUENCY_MAX);
hr = DSERR_INVALIDPARAM;
}
// Only set the frequency if it's changed
if(SUCCEEDED(hr) && dwFrequency == m_dwFrequency)
{
fContinue = FALSE;
}
// Update the 3D object
if(SUCCEEDED(hr) && m_p3dBuffer && fContinue)
{
hr = m_p3dBuffer->SetFrequency(dwFrequency, &fContinue);
}
// Update the device buffer
if(SUCCEEDED(hr) && fContinue)
{
hr = m_pDeviceBuffer->SetBufferFrequency(dwFrequency);
}
// Update our local copy
if(SUCCEEDED(hr))
{
m_dwFrequency = dwFrequency;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetPan
*
* Description:
* Retrieves pan for the given buffer.
*
* Arguments:
* LPLONG [out]: receives the pan.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetPan"
HRESULT CDirectSoundSecondaryBuffer::GetPan(LPLONG plPan)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN");
hr = DSERR_CONTROLUNAVAIL;
}
if(SUCCEEDED(hr))
{
*plPan = m_lPan;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetPan
*
* Description:
* Sets the pan for a given buffer.
*
* Arguments:
* LONG [in]: new pan.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetPan"
HRESULT CDirectSoundSecondaryBuffer::SetPan(LONG lPan)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPAN))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLPAN");
hr = DSERR_CONTROLUNAVAIL;
}
// Set the pan if it has changed
if(SUCCEEDED(hr) && lPan != m_lPan)
{
hr = SetAttenuation(m_lVolume, lPan);
// Update our local copy
if(SUCCEEDED(hr))
{
m_lPan = lPan;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetVolume
*
* Description:
* Retrieves volume for the given buffer.
*
* Arguments:
* LPLONG [out]: receives the volume.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVolume"
HRESULT CDirectSoundSecondaryBuffer::GetVolume(LPLONG plVolume)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME");
hr = DSERR_CONTROLUNAVAIL;
}
if(SUCCEEDED(hr))
{
*plVolume = m_lVolume;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetVolume
*
* Description:
* Sets the volume for a given buffer.
*
* Arguments:
* LONG [in]: new volume.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetVolume"
HRESULT CDirectSoundSecondaryBuffer::SetVolume(LONG lVolume)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLVOLUME");
hr = DSERR_CONTROLUNAVAIL;
}
// Set the volume if it has changed
if(SUCCEEDED(hr) && lVolume != m_lVolume)
{
#ifdef FUTURE_MULTIPAN_SUPPORT
if (m_dsbd.dwFlags & DSBCAPS_CTRLCHANNELVOLUME)
{
hr = m_pDeviceBuffer->SetChannelAttenuations(lVolume, m_dwChannelCount, m_pdwChannels, m_plChannelVolumes);
}
else
#endif
{
hr = SetAttenuation(lVolume, m_lPan);
}
// Update our local copy
if(SUCCEEDED(hr))
{
m_lVolume = lVolume;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetAttenuation
*
* Description:
* Obtains the buffer's true current attenuation, after 3D processing
* (unlike GetVolume, which returns the last volume set by the app).
*
* Arguments:
* FLOAT* [out]: attenuation in millibels.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetAttenuation"
HRESULT CDirectSoundSecondaryBuffer::GetAttenuation(FLOAT* pfAttenuation)
{
DPF_ENTER();
// FIXME: this function needs to obtain the buffer's true attenuation
// (i.e. the attenuation set via SetVolume() plus the extra attenuation
// caused by DS3D processing). Unfortunately we don't have a method in
// our device buffer class hierarchy (vad.h - CRenderWaveBuffer et al)
// to obtain a buffer's attenuation. And the code in ds3d.cpp doesn't
// explicitly save this info either (it just passes it along to the 3D
// object implemenation - which in some cases is external to dsound,
// e.g. ks3d.cpp).
//
// So we have two options:
//
// - Add a GetVolume() to the CSecondaryRenderWaveBuffer hierarchy;
// In some cases it can read the volume directly off the buffer
// (e.g. for KS buffers); in others (e.g. VxD buffers) the DDI
// doesn't provide for that, so we'd have to remember the last
// successfully set volume and return that (this last may be the
// best implementation; in fact it may be possibly to do it just
// once, in the base class).
//
// - Make the C3dObject hierarchy do attenuation calculations for
// all 3d objects (even KS ones that don't require it), and save
// the result.
//
// The first option looks much easier.
// (MANBUG 39130 - POSTPONED TO DX8.1)
HRESULT hr = DS_OK;
*pfAttenuation = 0.0f;
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetAttenuation
*
* Description:
* Sets the volume and pan for a given buffer.
*
* Arguments:
* LONG [in]: new volume.
* LONG [in]: new pan.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetAttenuation"
HRESULT CDirectSoundSecondaryBuffer::SetAttenuation(LONG lVolume, LONG lPan)
{
BOOL fContinue = TRUE;
HRESULT hr = DS_OK;
DSVOLUMEPAN dsvp;
DPF_ENTER();
// Calculate the attenuation based on the volume and pan
if(SUCCEEDED(hr) && fContinue)
{
FillDsVolumePan(lVolume, lPan, &dsvp);
}
// Update the 3D object
if(SUCCEEDED(hr) && m_p3dBuffer && fContinue)
{
hr = m_p3dBuffer->SetAttenuation(&dsvp, &fContinue);
}
// Update the device buffer
if(SUCCEEDED(hr) && fContinue)
{
hr = m_pDeviceBuffer->SetAttenuation(&dsvp);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetNotificationPositions
*
* Description:
* Sets buffer notification positions.
*
* Arguments:
* DWORD [in]: DSBPOSITIONNOTIFY structure count.
* LPDSBPOSITIONNOTIFY [in]: offsets and events.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetNotificationPositions"
HRESULT CDirectSoundSecondaryBuffer::SetNotificationPositions(DWORD dwCount, LPCDSBPOSITIONNOTIFY paNotes)
{
HRESULT hr = DS_OK;
LPDSBPOSITIONNOTIFY paNotesOrdered = NULL;
DWORD dwState;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLPOSITIONNOTIFY");
hr = DSERR_CONTROLUNAVAIL;
}
// Validate notifications
if(SUCCEEDED(hr))
{
hr = ValidateNotificationPositions(m_dsbd.dwBufferBytes, dwCount, paNotes, m_dsbd.lpwfxFormat->nBlockAlign, &paNotesOrdered);
}
// We must be stopped in order to set notification positions
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->GetState(&dwState);
if(SUCCEEDED(hr) && dwState & VAD_BUFFERSTATE_STARTED)
{
RPF(DPFLVL_ERROR, "Buffer must be stopped before setting notification positions");
hr = DSERR_INVALIDCALL;
}
}
// Set notifications
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->SetNotificationPositions(dwCount, paNotesOrdered);
}
MEMFREE(paNotesOrdered);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetOwningSink
*
* Description:
* Sets the owning CDirectSoundSink object for this buffer.
*
* Arguments:
* CDirectSoundSink * [in]: The new the owning sink object.
*
* Returns:
* void
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetOwningSink"
void CDirectSoundSecondaryBuffer::SetOwningSink(CDirectSoundSink* pOwningSink)
{
DPF_ENTER();
ASSERT(m_dsbd.dwFlags & DSBCAPS_SINKIN);
ASSERT(m_pOwningSink == NULL);
CHECK_WRITE_PTR(pOwningSink);
m_pOwningSink = pOwningSink;
m_pOwningSink->AddRef();
m_pDeviceBuffer->SetOwningSink(pOwningSink);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* GetCurrentPosition
*
* Description:
* Gets the current play/write positions for the given buffer.
*
* Arguments:
* LPDWORD [out]: receives play cursor position.
* LPDWORD [out]: receives write cursor position.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetCurrentPosition"
HRESULT CDirectSoundSecondaryBuffer::GetCurrentPosition(LPDWORD pdwPlay, LPDWORD pdwWrite)
{
HRESULT hr = DS_OK;
DWORD dwPlay;
DWORD dwWrite;
DPF_ENTER();
// Forbid certain calls for MIXIN and SINKIN buffers
if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN))
{
RPF(DPFLVL_ERROR, "GetCurrentPosition() not valid for MIXIN/sink buffers");
hr = DSERR_INVALIDCALL;
}
// Check for BUFFERLOST
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST))
{
hr = DSERR_BUFFERLOST;
}
// We save the position to local variables so that the object we're
// calling into doesn't have to worry about whether one or both of
// the arguments are NULL.
if(SUCCEEDED(hr))
{
if( m_pDirectSound->m_ahAppHacks.vdtCachePositions & m_pDirectSound->m_pDevice->m_vdtDeviceType )
{
// App hack for Furby calling GetCurrentPosition every .5ms on multiple buffers which stresses NT/WDM systems
DWORD dwNow = timeGetTime();
if( m_dwAHLastGetPosTime > 0 &&
dwNow >= m_dwAHLastGetPosTime && // catch unlikely wrap-around and '=' because of 5ms accuracy of timeGetTime()
dwNow - m_dwAHLastGetPosTime < 5 ) // 5ms tolerance
{
dwPlay = m_dwAHCachedPlayPos;
dwWrite = m_dwAHCachedWritePos;
}
else
{
hr = m_pDeviceBuffer->GetCursorPosition(&dwPlay, &dwWrite);
m_dwAHCachedPlayPos = dwPlay;
m_dwAHCachedWritePos = dwWrite;
}
m_dwAHLastGetPosTime = dwNow;
}
else
{
hr = m_pDeviceBuffer->GetCursorPosition(&dwPlay, &dwWrite);
}
}
// Block-align the positions
if(SUCCEEDED(hr))
{
dwPlay = BLOCKALIGN(dwPlay, m_dsbd.lpwfxFormat->nBlockAlign);
dwWrite = BLOCKALIGN(dwWrite, m_dsbd.lpwfxFormat->nBlockAlign);
}
// Apply app-hacks and cursor adjustments
if(SUCCEEDED(hr))
{
// If the buffer has effects, we return the FX cursor as the write cursor
if(HasFX())
{
DWORD dwDistance = BytesToMs(DISTANCE(dwWrite, m_dwSliceEnd, GetBufferSize()), Format());
if (dwDistance > 200)
DPF(DPFLVL_WARNING, "FX cursor suspiciously far ahead of write cursor (%ld ms)", dwDistance);
else
dwWrite = m_dwSliceEnd; // FIXME: may not always be valid
}
if (m_pDirectSound->m_ahAppHacks.lCursorPad)
{
dwPlay = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad);
dwWrite = PadCursor(dwWrite, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.lCursorPad);
}
if(m_pDirectSound->m_ahAppHacks.vdtReturnWritePos & m_pDirectSound->m_pDevice->m_vdtDeviceType)
{
dwPlay = dwWrite;
}
if(m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.fEnable)
{
dwWrite = PadCursor(dwPlay, m_dsbd.dwBufferBytes, m_dsbd.lpwfxFormat, m_pDirectSound->m_ahAppHacks.swpSmoothWritePos.lCursorPad);
}
}
// Success
if(SUCCEEDED(hr) && pdwPlay)
{
*pdwPlay = dwPlay;
}
if(SUCCEEDED(hr) && pdwWrite)
{
*pdwWrite = dwWrite;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetCurrentPosition
*
* Description:
* Sets the current play position for a given buffer.
*
* Arguments:
* DWORD [in]: new play position.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetCurrentPosition"
HRESULT CDirectSoundSecondaryBuffer::SetCurrentPosition(DWORD dwPlay)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Forbid certain calls for MIXIN and SINKIN buffers
if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN))
{
RPF(DPFLVL_ERROR, "SetCurrentPosition() not valid for MIXIN/sink buffers");
hr = DSERR_INVALIDCALL;
}
// Check for BUFFERLOST
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST))
{
hr = DSERR_BUFFERLOST;
}
// Check the cursor position
if(SUCCEEDED(hr) && dwPlay >= m_dsbd.dwBufferBytes)
{
RPF(DPFLVL_ERROR, "Cursor position out of bounds");
hr = DSERR_INVALIDPARAM;
}
// Make sure dwPlay is block-aligned
if(SUCCEEDED(hr))
{
dwPlay = BLOCKALIGN(dwPlay, m_dsbd.lpwfxFormat->nBlockAlign);
}
// Prime the effects chain for the new play position
if(SUCCEEDED(hr) && HasFX())
{
hr = m_fxChain->PreRollFx(dwPlay);
}
if(SUCCEEDED(hr))
{
hr = m_pDeviceBuffer->SetCursorPosition(dwPlay);
}
// Mark the play state as stopped to force the streaming thread
// to react to our new cursor position
if(SUCCEEDED(hr))
{
m_playState = Stopped;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetStatus
*
* Description:
* Retrieves status for the given buffer.
*
* Arguments:
* LPDWORD [out]: receives the status.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetStatus"
HRESULT CDirectSoundSecondaryBuffer::GetStatus(LPDWORD pdwStatus)
{
HRESULT hr = DS_OK;
DWORD dwStatus;
DWORD dwState;
VADRBUFFERCAPS vrbc;
DPF_ENTER();
// Update the buffer status. If we're lost, that's the only state we care about
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
dwStatus = DSBSTATUS_BUFFERLOST;
}
else
{
// Get the current device buffer state
hr = m_pDeviceBuffer->GetState(&dwState);
if(SUCCEEDED(hr))
{
dwStatus = m_dwStatus;
UpdateBufferStatusFlags(dwState, &m_dwStatus);
// If we thought we were playing, but now we're stopped, handle
// the transition.
if((dwStatus & DSBSTATUS_PLAYING) && !(m_dwStatus & DSBSTATUS_PLAYING))
{
hr = Stop();
}
}
// Fill in the buffer location
if(SUCCEEDED(hr))
{
m_dwStatus &= ~DSBSTATUS_LOCMASK;
if(m_dwStatus & DSBSTATUS_RESOURCESACQUIRED)
{
hr = m_pDeviceBuffer->GetCaps(&vrbc);
if(SUCCEEDED(hr))
{
m_dwStatus |= DSBCAPStoDSBSTATUS(vrbc.dwFlags);
}
}
}
if(SUCCEEDED(hr))
{
dwStatus = m_dwStatus;
}
}
// Mask off bits that shouldn't get back to the app
if(SUCCEEDED(hr))
{
dwStatus &= DSBSTATUS_USERMASK;
}
if(SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
dwStatus &= ~DSBSTATUS_LOCDEFERMASK;
}
if(SUCCEEDED(hr) && pdwStatus)
{
*pdwStatus = dwStatus;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Play
*
* Description:
* Starts the buffer playing.
*
* Arguments:
* DWORD [in]: priority.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Play"
HRESULT CDirectSoundSecondaryBuffer::Play(DWORD dwPriority, DWORD dwFlags)
{
#ifdef DEBUG
const ULONG ulKsIoctlCount = g_ulKsIoctlCount;
#endif // DEBUG
DWORD dwState = VAD_BUFFERSTATE_STARTED;
HRESULT hr = DS_OK;
DPF_ENTER();
// Make sure cooperative level has been set
if(SUCCEEDED(hr) && (!m_pDirectSound->m_dsclCooperativeLevel.dwThreadId || DSSCL_NONE == m_pDirectSound->m_dsclCooperativeLevel.dwPriority))
{
RPF(DPFLVL_ERROR, "Cooperative level must be set before calling Play");
hr = DSERR_PRIOLEVELNEEDED;
}
// Priority is only valid if we're LOCDEFER
if(SUCCEEDED(hr) && dwPriority && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
RPF(DPFLVL_ERROR, "Priority is only valid on LOCDEFER buffers");
hr = DSERR_INVALIDPARAM;
}
// Validate flags
if(SUCCEEDED(hr) && (dwFlags & DSBPLAY_LOCDEFERMASK) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
RPF(DPFLVL_ERROR, "Specified a flag that is only valid on LOCDEFER buffers");
hr = DSERR_INVALIDPARAM;
}
// For MIXIN/sink buffers, the DSBPLAY_LOOPING flag is mandatory
if(SUCCEEDED(hr) && GetBufferType() && !(dwFlags & DSBPLAY_LOOPING))
{
RPF(DPFLVL_ERROR, "The LOOPING flag must always be set for MIXIN/sink buffers");
hr = DSERR_INVALIDPARAM;
}
// Check for BUFFERLOST
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST))
{
hr = DSERR_BUFFERLOST;
}
// Refresh the current buffer status
if(SUCCEEDED(hr))
{
hr = GetStatus(NULL);
}
// Set buffer priority
if(SUCCEEDED(hr))
{
m_dwPriority = dwPriority;
}
// Reset the special success code
m_pDeviceBuffer->m_hrSuccessCode = DS_OK;
// Make sure resources have been acquired
if(SUCCEEDED(hr))
{
hr = AttemptResourceAcquisition(dwFlags);
}
// Set the buffer state
if(SUCCEEDED(hr))
{
if(dwFlags & DSBPLAY_LOOPING)
{
dwState |= VAD_BUFFERSTATE_LOOPING;
}
hr = SetBufferState(dwState);
}
if(SUCCEEDED(hr))
{
// If the buffer was previously terminated, remove the flag from the status
m_dwStatus &= ~DSBSTATUS_TERMINATED;
// Make it possible to steal this buffer's resources
m_fCanStealResources = TRUE;
}
// Save the result code
m_hrPlay = hr;
#ifdef DEBUG
if(IS_KS_VAD(m_pDirectSound->m_pDevice->m_vdtDeviceType))
{
DPF(DPFLVL_INFO, "%s used %lu IOCTLs", TEXT(DPF_FNAME), g_ulKsIoctlCount - ulKsIoctlCount);
}
#endif // DEBUG
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Stop
*
* Description:
* Stops playing the given buffer.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Stop"
HRESULT CDirectSoundSecondaryBuffer::Stop(void)
{
#ifdef DEBUG
const ULONG ulKsIoctlCount = g_ulKsIoctlCount;
#endif // DEBUG
HRESULT hr = DS_OK;
DPF_ENTER();
#ifdef ENABLE_PERFLOG
// Check if there were any glitches
if (m_pPerfState)
{
m_pPerfState->OnUnlockBuffer(0, GetBufferSize());
}
#endif
// Check for BUFFERLOST
if(m_dwStatus & DSBSTATUS_BUFFERLOST)
{
hr = DSERR_BUFFERLOST;
}
// Set the buffer state
if(SUCCEEDED(hr))
{
hr = SetBufferState(VAD_BUFFERSTATE_STOPPED);
}
// If we're LOCDEFER and the buffer is stopped, resources can be freed
if(SUCCEEDED(hr) && (m_dsbd.dwFlags & DSBCAPS_LOCDEFER) && (m_dwStatus & DSBSTATUS_RESOURCESACQUIRED))
{
hr = FreeResources(FALSE);
}
#ifdef DEBUG
if(IS_KS_VAD(m_pDirectSound->m_pDevice->m_vdtDeviceType))
{
DPF(DPFLVL_MOREINFO, "%s used %lu IOCTLs", TEXT(DPF_FNAME), g_ulKsIoctlCount - ulKsIoctlCount);
}
#endif // DEBUG
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetBufferState
*
* Description:
* Sets the buffer play/stop state.
*
* Arguments:
* DWORD [in]: buffer state flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetBufferState"
HRESULT CDirectSoundSecondaryBuffer::SetBufferState(DWORD dwNewState)
{
DWORD dwOldState;
HRESULT hr;
DPF_ENTER();
hr = m_pDeviceBuffer->GetState(&dwOldState);
if(SUCCEEDED(hr) && dwNewState != dwOldState)
{
// Our state is changing; reset the performance tracing state
#ifdef ENABLE_PERFLOG
if (PerflogTracingEnabled())
{
if (!m_pPerfState)
m_pPerfState = NEW(BufferPerfState(this));
if (m_pPerfState)
m_pPerfState->Reset();
}
#endif
DPF(DPFLVL_MOREINFO, "Buffer at 0x%p going from %s to %s", this, StateName(dwOldState), StateName(dwNewState));
hr = m_pDeviceBuffer->SetState(dwNewState);
if (SUCCEEDED(hr) && HasSink())
{
#ifdef FUTURE_WAVE_SUPPORT
if ((m_dsbd.dwFlags & DSBCAPS_FROMWAVEOBJECT) && (dwNewState & VAD_BUFFERSTATE_STARTED))
hr = m_pOwningSink->Activate(TRUE);
// FIXME: maybe this activation should be handled by the sink
// itself in SetBufferState() below, so it can also take care
// of deactivation when it runs out of active clients
if (SUCCEEDED(hr))
#endif // FUTURE_WAVE_SUPPORT
hr = m_pOwningSink->SetBufferState(this, dwNewState, dwOldState);
}
if (SUCCEEDED(hr) && HasFX())
hr = m_fxChain->NotifyState(dwNewState);
// If a MIXIN or SINKIN buffer is stopping, clear it and set its position to 0
if (SUCCEEDED(hr) && GetBufferType() && !(dwNewState & VAD_BUFFERSTATE_STARTED))
{
ClearWriteBuffer(); // FIXME - does this simplify the sink?
ClearPlayBuffer();
m_pDeviceBuffer->SetCursorPosition(0);
m_playState = Stopped; // This stops FX processing on this buffer,
// and forces the streaming thread to reset
// our current slice next time it wakes up
m_dwSliceBegin = m_dwSliceEnd = MAX_DWORD;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Activate
*
* Description:
* Activates or deactivates the buffer object.
*
* Arguments:
* BOOL [in]: Activation state. TRUE to activate, FALSE to deactivate.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Activate"
HRESULT CDirectSoundSecondaryBuffer::Activate(BOOL fActive)
{
HRESULT hr;
DPF_ENTER();
hr = SetMute(!fActive);
if(SUCCEEDED(hr))
{
if(fActive)
{
m_dwStatus |= DSBSTATUS_ACTIVE;
// If we're a MIXIN or SINKIN buffer, we have to clear our lost
// status (since the app can't call Restore() to do it for us)
if (GetBufferType())
{
// If the buffer was playing before it got lost, restart it
if (m_dwStatus & DSBSTATUS_STOPPEDBYFOCUS)
hr = SetBufferState(VAD_BUFFERSTATE_STARTED | VAD_BUFFERSTATE_LOOPING);
// Clear our BUFFERLOST and STOPPEDBYFOCUS status flags
m_dwStatus &= ~(DSBSTATUS_BUFFERLOST | DSBSTATUS_STOPPEDBYFOCUS);
}
}
else
{
m_dwStatus &= ~DSBSTATUS_ACTIVE;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetMute
*
* Description:
* Mutes or unmutes the buffer.
*
* Arguments:
* BOOL [in]: Mute state.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetMute"
HRESULT CDirectSoundSecondaryBuffer::SetMute(BOOL fMute)
{
BOOL fContinue = TRUE;
HRESULT hr = DS_OK;
DPF_ENTER();
// Only set the mute status if it's changed
if(SUCCEEDED(hr) && fMute == m_fMute)
{
fContinue = FALSE;
}
// Update the 3D object
if(SUCCEEDED(hr) && m_p3dBuffer && fContinue)
{
hr = m_p3dBuffer->SetMute(fMute, &fContinue);
}
// Update the device buffer
if(SUCCEEDED(hr) && fContinue)
{
hr = m_pDeviceBuffer->SetMute(fMute);
}
// Update our local copy
if(SUCCEEDED(hr))
{
m_fMute = fMute;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Lock
*
* Description:
* Locks the buffer memory to allow for writing.
*
* Arguments:
* DWORD [in]: offset, in bytes, from the start of the buffer to where
* the lock begins. This parameter is ignored if
* DSBLOCK_FROMWRITECURSOR is specified in the dwFlags
* parameter.
* DWORD [in]: size, in bytes, of the portion of the buffer to lock.
* Note that the sound buffer is conceptually circular.
* LPVOID * [out]: address for a pointer to contain the first block of
* the sound buffer to be locked.
* LPDWORD [out]: address for a variable to contain the number of bytes
* pointed to by the ppvAudioPtr1 parameter. If this
* value is less than the dwWriteBytes parameter,
* ppvAudioPtr2 will point to a second block of sound
* data.
* LPVOID * [out]: address for a pointer to contain the second block of
* the sound buffer to be locked. If the value of this
* parameter is NULL, the ppvAudioPtr1 parameter
* points to the entire locked portion of the sound
* buffer.
* LPDWORD [out]: address of a variable to contain the number of bytes
* pointed to by the ppvAudioPtr2 parameter. If
* ppvAudioPtr2 is NULL, this value will be 0.
* DWORD [in]: locking flags
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Lock"
HRESULT CDirectSoundSecondaryBuffer::Lock(DWORD dwWriteCursor, DWORD dwWriteBytes, LPVOID *ppvAudioPtr1, LPDWORD pdwAudioBytes1, LPVOID *ppvAudioPtr2, LPDWORD pdwAudioBytes2, DWORD dwFlags)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Forbid certain calls for MIXIN and SINKIN buffers
if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN))
{
RPF(DPFLVL_ERROR, "Lock() not valid for MIXIN/sink buffers");
hr = DSERR_INVALIDCALL;
}
// Check for BUFFERLOST
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST))
{
hr = DSERR_BUFFERLOST;
}
// Handle flags
if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_FROMWRITECURSOR))
{
hr = GetCurrentPosition(NULL, &dwWriteCursor);
}
if(SUCCEEDED(hr) && (dwFlags & DSBLOCK_ENTIREBUFFER))
{
dwWriteBytes = m_dsbd.dwBufferBytes;
}
// Cursor validation
if(SUCCEEDED(hr) && dwWriteCursor >= m_dsbd.dwBufferBytes)
{
ASSERT(!(dwFlags & DSBLOCK_FROMWRITECURSOR));
RPF(DPFLVL_ERROR, "Write cursor past buffer end");
hr = DSERR_INVALIDPARAM;
}
if(SUCCEEDED(hr) && dwWriteBytes > m_dsbd.dwBufferBytes)
{
ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER));
RPF(DPFLVL_ERROR, "Lock size larger than buffer size");
hr = DSERR_INVALIDPARAM;
}
if(SUCCEEDED(hr) && !dwWriteBytes)
{
ASSERT(!(dwFlags & DSBLOCK_ENTIREBUFFER));
RPF(DPFLVL_ERROR, "Lock size must be > 0");
hr = DSERR_INVALIDPARAM;
}
// Lock the device buffer
if(SUCCEEDED(hr))
{
if (GetDsVersion() >= DSVERSION_DX8)
{
// DX8 removes support for apps that lock their buffers
// and never bother to unlock them again (see the comment
// in CVxdSecondaryRenderWaveBuffer::Lock for explanation)
hr = DirectLock(dwWriteCursor, dwWriteBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2);
}
else
{
hr = m_pDeviceBuffer->Lock(dwWriteCursor, dwWriteBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2);
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Unlock
*
* Description:
* Unlocks the given buffer.
*
* Arguments:
* LPVOID [in]: pointer to the first block.
* DWORD [in]: size of the first block.
* LPVOID [in]: pointer to the second block.
* DWORD [in]: size of the second block.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Unlock"
HRESULT CDirectSoundSecondaryBuffer::Unlock(LPVOID pvAudioPtr1, DWORD dwAudioBytes1, LPVOID pvAudioPtr2, DWORD dwAudioBytes2)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Forbid certain calls for MIXIN and SINKIN buffers
if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN))
{
RPF(DPFLVL_ERROR, "Unlock() not valid for MIXIN/sink buffers");
hr = DSERR_INVALIDCALL;
}
// Check for BUFFERLOST
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST))
{
hr = DSERR_BUFFERLOST;
}
// Unlock the device buffer
if(SUCCEEDED(hr))
{
if (GetDsVersion() >= DSVERSION_DX8)
{
// DX8 removes support for apps that lock their buffers
// and never bother to unlock them again (see the comment
// in CVxdSecondaryRenderWaveBuffer::Lock for explanation)
hr = DirectUnlock(pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2);
}
else
{
hr = m_pDeviceBuffer->Unlock(pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2);
}
}
// Update the processed FX buffer if necessary
if(SUCCEEDED(hr) && HasFX())
{
m_fxChain->UpdateFx(pvAudioPtr1, dwAudioBytes1);
if (pvAudioPtr2 && dwAudioBytes2)
m_fxChain->UpdateFx(pvAudioPtr2, dwAudioBytes2);
}
#ifdef ENABLE_PERFLOG
// Check if there were any glitches
if (m_pPerfState)
{
if (pvAudioPtr1)
m_pPerfState->OnUnlockBuffer(PtrDiffToUlong(LPBYTE(pvAudioPtr1) - GetPlayBuffer()), dwAudioBytes1);
if (pvAudioPtr2)
m_pPerfState->OnUnlockBuffer(PtrDiffToUlong(LPBYTE(pvAudioPtr2) - GetPlayBuffer()), dwAudioBytes2);
}
#endif
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* Lose
*
* Description:
* Flags the buffer as lost.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Lose"
HRESULT CDirectSoundSecondaryBuffer::Lose(void)
{
DPF_ENTER();
if(!(m_dwStatus & DSBSTATUS_BUFFERLOST))
{
// If the buffer is MIXIN or SINKIN, and is currently playing,
// flag it as stopped due to a focus change
if (GetBufferType())
{
DWORD dwState = 0;
m_pDeviceBuffer->GetState(&dwState);
if (dwState & VAD_BUFFERSTATE_STARTED)
m_dwStatus |= DSBSTATUS_STOPPEDBYFOCUS;
}
// Stop the buffer. All lost buffers are stopped by definition.
SetBufferState(VAD_BUFFERSTATE_STOPPED);
// Flag the buffer as lost
m_dwStatus |= DSBSTATUS_BUFFERLOST;
// Deactivate the buffer
Activate(FALSE);
// Free any open locks on the buffer
m_pDeviceBuffer->OverrideLocks();
}
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
/***************************************************************************
*
* Restore
*
* Description:
* Attempts to restore a lost bufer.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::Restore"
HRESULT CDirectSoundSecondaryBuffer::Restore(void)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Forbid certain calls for MIXIN and SINKIN buffers
if(m_dsbd.dwFlags & (DSBCAPS_MIXIN | DSBCAPS_SINKIN))
{
RPF(DPFLVL_ERROR, "Restore() not valid for MIXIN/sink buffers");
hr = DSERR_INVALIDCALL;
}
if(SUCCEEDED(hr) && (m_dwStatus & DSBSTATUS_BUFFERLOST))
{
// Are we still lost?
if(DSBUFFERFOCUS_LOST == g_pDsAdmin->GetBufferFocusState(this))
{
hr = DSERR_BUFFERLOST;
}
else
{
m_dwStatus &= ~DSBSTATUS_BUFFERLOST;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetVoiceManagerMode
*
* Description:
* Gets the current voice manager mode.
*
* Arguments:
* VmMode * [out]: receives voice manager mode.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVoiceManagerMode"
HRESULT CDirectSoundSecondaryBuffer::GetVoiceManagerMode(VmMode *pvmmMode)
{
DPF_ENTER();
*pvmmMode = m_pDirectSound->m_vmmMode;
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
/***************************************************************************
*
* SetVoiceManagerMode
*
* Description:
* Sets the current voice manager mode.
*
* Arguments:
* VmMode [in]: voice manager mode.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetVoiceManagerMode"
HRESULT CDirectSoundSecondaryBuffer::SetVoiceManagerMode(VmMode vmmMode)
{
HRESULT hr = DS_OK;
DPF_ENTER();
if(vmmMode < DSPROPERTY_VMANAGER_MODE_FIRST || vmmMode > DSPROPERTY_VMANAGER_MODE_LAST)
{
RPF(DPFLVL_ERROR, "Invalid Voice Manager mode");
hr = DSERR_INVALIDPARAM;
}
if(SUCCEEDED(hr))
{
m_pDirectSound->m_vmmMode = vmmMode;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetVoiceManagerPriority
*
* Description:
* Gets the current voice manager priority.
*
* Arguments:
* LPDWORD [out]: receives voice manager priority.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVoiceManagerPriority"
HRESULT CDirectSoundSecondaryBuffer::GetVoiceManagerPriority(LPDWORD pdwPriority)
{
DPF_ENTER();
*pdwPriority = m_dwVmPriority;
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
/***************************************************************************
*
* SetVoiceManagerPriority
*
* Description:
* Sets the current voice manager priority.
*
* Arguments:
* DWORD [in]: voice manager priority.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetVoiceManagerPriority"
HRESULT CDirectSoundSecondaryBuffer::SetVoiceManagerPriority(DWORD dwPriority)
{
DPF_ENTER();
m_dwVmPriority = dwPriority;
DPF_LEAVE_HRESULT(DS_OK);
return DS_OK;
}
#ifdef DEAD_CODE
/***************************************************************************
*
* GetVoiceManagerState
*
* Description:
* Gets the current voice manager state.
*
* Arguments:
* VmState * [out]: receives voice manager state.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetVoiceManagerState"
HRESULT CDirectSoundSecondaryBuffer::GetVoiceManagerState(VmState *pvmsState)
{
DWORD dwStatus;
HRESULT hr;
DPF_ENTER();
hr = GetStatus(&dwStatus);
if(SUCCEEDED(hr))
{
if(dwStatus & DSBSTATUS_PLAYING)
{
*pvmsState = DSPROPERTY_VMANAGER_STATE_PLAYING3DHW;
}
else if(FAILED(m_hrPlay))
{
*pvmsState = DSPROPERTY_VMANAGER_STATE_PLAYFAILED;
}
else if(dwStatus & DSBSTATUS_TERMINATED)
{
*pvmsState = DSPROPERTY_VMANAGER_STATE_BUMPED;
}
else
{
ASSERT(!dwStatus);
*pvmsState = DSPROPERTY_VMANAGER_STATE_SILENT;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
#endif // DEAD_CODE
/***************************************************************************
*
* SetFX
*
* Description:
* Sets a chain of effects on this buffer, replacing any previous
* effect chain and, if necessary, allocating or deallocating the
* shadow buffer used to hold unprocessed audio .
*
* Arguments:
* DWORD [in]: Number of effects. 0 to remove current FX chain.
* DSEFFECTDESC * [in]: Array of effect descriptor structures.
* DWORD * [out]: Receives the creation statuses of the effects.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFX"
HRESULT CDirectSoundSecondaryBuffer::SetFX(DWORD dwFxCount, LPDSEFFECTDESC pDSFXDesc, LPDWORD pdwResultCodes)
{
DWORD dwStatus;
HRESULT hr = DS_OK;
DPF_ENTER();
ASSERT(IS_VALID_READ_PTR(pDSFXDesc, dwFxCount * sizeof *pDSFXDesc));
ASSERT(!pdwResultCodes || IS_VALID_WRITE_PTR(pdwResultCodes, dwFxCount * sizeof *pdwResultCodes));
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFX))
{
RPF(DPFLVL_ERROR, "Buffer was not created with DSBCAPS_CTRLFX flag");
hr = DSERR_CONTROLUNAVAIL;
}
// Check the buffer is inactive
if(SUCCEEDED(hr))
{
hr = GetStatus(&dwStatus);
if(SUCCEEDED(hr) && (dwStatus & DSBSTATUS_PLAYING))
{
RPF(DPFLVL_ERROR, "Cannot change effects, because buffer is playing");
hr = DSERR_INVALIDCALL;
}
}
// Check there are no pending locks on the buffer
if(SUCCEEDED(hr) && m_pDeviceBuffer->m_pSysMemBuffer->GetLockCount())
{
RPF(DPFLVL_ERROR, "Cannot change effects, because buffer has pending locks");
hr = DSERR_INVALIDCALL;
}
if(SUCCEEDED(hr))
{
// Release the old FX chain, if necessary
RELEASE(m_fxChain);
// If the effects count is 0, we can free up associated resources
if (dwFxCount == 0)
{
m_pDeviceBuffer->m_pSysMemBuffer->FreeFxBuffer();
}
else // Allocate the pre-FX buffer and create the FX chain requested
{
hr = m_pDeviceBuffer->m_pSysMemBuffer->AllocateFxBuffer();
if (SUCCEEDED(hr))
{
m_fxChain = NEW(CEffectChain(this));
hr = HRFROMP(m_fxChain);
}
if (SUCCEEDED(hr))
{
hr = m_fxChain->Initialize(dwFxCount, pDSFXDesc, pdwResultCodes);
}
if (SUCCEEDED(hr))
{
if (!(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
hr = m_fxChain->AcquireFxResources();
}
// We need to preserve the return code from AcquireFxResources, in case it's
// DS_INCOMPLETE, so we omit "hr=" from GetFxStatus (which always succeeds):
if (pdwResultCodes)
{
m_fxChain->GetFxStatus(pdwResultCodes);
}
}
if (FAILED(hr))
{
RELEASE(m_fxChain);
m_pDeviceBuffer->m_pSysMemBuffer->FreeFxBuffer();
}
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetFXBufferConfig
*
* Description:
* Sets a chain of effects described in a CDirectSoundBufferConfig
* object, which represents a buffer description previously loaded
* from a file (or other IStream provider).
*
* Arguments:
* CDirectSoundBufferConfig * [in]: describes the effects to be set.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetFXBufferConfig"
HRESULT CDirectSoundSecondaryBuffer::SetFXBufferConfig(CDirectSoundBufferConfig* pDSBConfigObj)
{
DWORD dwStatus;
HRESULT hr;
DPF_ENTER();
CHECK_READ_PTR(pDSBConfigObj);
ASSERT(m_dsbd.dwFlags & DSBCAPS_CTRLFX);
hr = GetStatus(&dwStatus);
if(SUCCEEDED(hr) && (dwStatus & DSBSTATUS_PLAYING))
{
DPF(DPFLVL_ERROR, "Cannot change effects, because buffer is playing");
hr = DSERR_GENERIC;
}
if(SUCCEEDED(hr))
{
// Release the old FX chain, if necessary
RELEASE(m_fxChain);
// Allocate the pre-FX buffer and create the FX chain requested
hr = m_pDeviceBuffer->m_pSysMemBuffer->AllocateFxBuffer();
if (SUCCEEDED(hr))
{
m_fxChain = NEW(CEffectChain(this));
hr = HRFROMP(m_fxChain);
}
if (SUCCEEDED(hr))
{
hr = m_fxChain->Clone(pDSBConfigObj);
}
if (SUCCEEDED(hr) && !(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
hr = m_fxChain->AcquireFxResources();
}
if (FAILED(hr))
{
RELEASE(m_fxChain);
m_pDeviceBuffer->m_pSysMemBuffer->FreeFxBuffer();
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* UserAcquireResources
*
* Description:
* Acquires hardware resources, and reports on FX creation status.
* The "User" means this is called only from the app (via dsimp.cpp).
*
* Arguments:
* DWORD [in]: count of FX status flags to be returned.
* LPDWORD [out]: pointer to array of FX status flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::UserAcquireResources"
HRESULT CDirectSoundSecondaryBuffer::UserAcquireResources(DWORD dwFlags, DWORD dwFxCount, LPDWORD pdwResultCodes)
{
HRESULT hr = DS_OK;
DPF_ENTER();
// Check that buffer is LOCDEFER
if(!(m_dsbd.dwFlags & DSBCAPS_LOCDEFER))
{
RPF(DPFLVL_ERROR, "AcquireResources() is only valid for buffers created with DSBCAPS_LOCDEFER");
hr = DSERR_INVALIDCALL;
}
if (SUCCEEDED(hr) && pdwResultCodes && (!HasFX() || dwFxCount != m_fxChain->GetFxCount()))
{
RPF(DPFLVL_ERROR, "Specified an incorrect effect count");
hr = DSERR_INVALIDPARAM;
}
if (SUCCEEDED(hr))
hr = AttemptResourceAcquisition(dwFlags);
// We need to preserve the return code from AttemptResourceAcquisition, in case it's
// DS_INCOMPLETE, so we omit the "hr=" from GetFxStatus (which always succeeds):
if (HasFX() && pdwResultCodes)
m_fxChain->GetFxStatus(pdwResultCodes);
// If successful, prevent this buffer from having its resources stolen before it's played
if (SUCCEEDED(hr))
m_fCanStealResources = FALSE;
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetObjectInPath
*
* Description:
* Obtains a given interface on a given effect on this buffer.
*
* Arguments:
* REFGUID [in]: Class ID of the effect that is being searched for,
* or GUID_ALL_OBJECTS to search for any effect.
* DWORD [in]: Index of the effect, in case there is more than one
* effect with this CLSID on this buffer.
* REFGUID [in]: IID of the interface requested. The selected effect
* will be queried for this interface.
* LPVOID * [out]: Receives the interface requested.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetObjectInPath"
HRESULT CDirectSoundSecondaryBuffer::GetObjectInPath(REFGUID guidObject, DWORD dwIndex, REFGUID iidInterface, LPVOID *ppObject)
{
HRESULT hr;
DPF_ENTER();
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLFX))
{
RPF(DPFLVL_ERROR, "Buffer was not created with DSBCAPS_CTRLFX flag");
hr = DSERR_CONTROLUNAVAIL;
}
if (!HasFX())
{
hr = DSERR_OBJECTNOTFOUND;
}
else
{
hr = m_fxChain->GetEffectInterface(guidObject, dwIndex, iidInterface, ppObject);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetInternalCursors
*
* Description:
* This method is used by streamer.cpp and effects.cpp (new in DX8).
* It obtains the current play and write cursors from our contained
* m_pDeviceBuffer object, and aligns them on sample block boundaries.
*
* Arguments:
* LPDWORD [out]: receives the play position.
* LPDWORD [out]: receives the write position.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetInternalCursors"
HRESULT CDirectSoundSecondaryBuffer::GetInternalCursors(LPDWORD pdwPlay, LPDWORD pdwWrite)
{
DPF_ENTER();
HRESULT hr = m_pDeviceBuffer->GetCursorPosition(pdwPlay, pdwWrite);
// ASSERT(SUCCEEDED(hr)); // Removed this ASSERT because the device will
// sometimes mysteriously disappear out from under us - which is a pity,
// because we depend utterly on GetCursorPosition() being reliable.
if (SUCCEEDED(hr))
{
// If our device is emulated, add EMULATION_LATENCY_BOOST ms to the write cursor
// FIXME: this code should be in m_pDeviceBuffer->GetCursorPosition() once we've
// figured out what's up with cursor reporting on emulation. For now, let's just
// avoid regressions! This method is only used by effects.cpp and dssink.cpp...
// DISABLED UNTIL DX8.1:
// if (pdwWrite && IsEmulated())
// *pdwWrite = PadCursor(*pdwWrite, GetBufferSize(), Format(), EMULATION_LATENCY_BOOST);
// OR:
// if (IsEmulated())
// {
// if (pdwPlay)
// *pdwPlay = PadCursor(*pdwPlay, GetBufferSize(), Format(), EMULATION_LATENCY_BOOST);
// if (pdwWrite)
// *pdwWrite = PadCursor(*pdwWrite, GetBufferSize(), Format(), EMULATION_LATENCY_BOOST);
// }
// The cursors aren't guaranteed to be on block boundaries - fix them:
if (pdwPlay)
*pdwPlay = BLOCKALIGN(*pdwPlay, Format()->nBlockAlign);
if (pdwWrite)
*pdwWrite = BLOCKALIGN(*pdwWrite, Format()->nBlockAlign);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetCurrentSlice
*
* Description:
* Obtains the part of the audio buffer that is being processed
* during the streaming thread's current pass.
*
* The "slice" terminology is whimsical but makes it easy to search
* for the slice-handling code in an editor. It's better than yet
* another overloaded usage of "buffer".
*
* Arguments:
* LPDWORD [out]: receives buffer slice start (as byte offset).
* LPDWORD [out]: receives buffer slice end (as byte offset).
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::GetCurrentSlice"
void CDirectSoundSecondaryBuffer::GetCurrentSlice(LPDWORD pdwSliceBegin, LPDWORD pdwSliceEnd)
{
DPF_ENTER();
// Make sure the slice endpoints have been initialized and are within range
if (!(m_dsbd.dwFlags & DSBCAPS_SINKIN))
{
// NB: Sink buffers can be uninitialized if the sink is starting,
// or if it decided not to advance its play position on this run.
ASSERT(m_dwSliceBegin != MAX_DWORD && m_dwSliceEnd != MAX_DWORD);
ASSERT(m_dwSliceBegin < GetBufferSize() && m_dwSliceEnd < GetBufferSize());
}
if (pdwSliceBegin) *pdwSliceBegin = m_dwSliceBegin;
if (pdwSliceEnd) *pdwSliceEnd = m_dwSliceEnd;
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* SetCurrentSlice
*
* Description:
* Establishes the part of this audio buffer that is being processed
* during the streaming thread's current pass.
*
* Arguments:
* DWORD [in]: Slice start (as byte offset from audio buffer start),
* or the special argument CURRENT_WRITE_POS which means
* "make the slice start at our current write position".
* DWORD [in]: Slice size in bytes.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetCurrentSlice"
void CDirectSoundSecondaryBuffer::SetCurrentSlice(DWORD dwSliceBegin, DWORD dwBytes)
{
HRESULT hr = DS_OK;
DPF_ENTER();
DPF_TIMING(DPFLVL_MOREINFO, "begin=%lu size=%lu (%s%s%sbuffer%s at 0x%p)", dwSliceBegin, dwBytes,
m_dsbd.dwFlags & DSBCAPS_MIXIN ? TEXT("MIXIN ") : TEXT(""),
m_dsbd.dwFlags & DSBCAPS_SINKIN ? TEXT("SINKIN ") : TEXT(""),
!(m_dsbd.dwFlags & (DSBCAPS_MIXIN|DSBCAPS_SINKIN)) ? TEXT("regular ") : TEXT(""),
HasFX() ? TEXT(" w/effects") : TEXT(""), this);
ASSERT(dwBytes > 0 && dwBytes < GetBufferSize());
if (dwSliceBegin == CURRENT_WRITE_POS)
{
hr = GetInternalCursors(NULL, &dwSliceBegin);
if (SUCCEEDED(hr))
{
m_dwSliceBegin = PadCursor(dwSliceBegin, GetBufferSize(), Format(), INITIAL_WRITEAHEAD);
DPF_TIMING(DPFLVL_MOREINFO, "CURRENT_WRITE_POS is %lu; setting slice start to %lu", dwSliceBegin, m_dwSliceBegin);
}
else // GetInternalCursors failed; stop FX processing and force the
{ // streaming thread to reset our slice next time it wakes up
m_playState = Stopped;
m_dwSliceBegin = m_dwSliceEnd = MAX_DWORD;
}
}
else // dwSliceBegin != CURRENT_WRITE_POS
{
// Normal case: set the new slice begin position explicitly
m_dwSliceBegin = dwSliceBegin;
}
if (SUCCEEDED(hr))
{
ASSERT(m_dwSliceBegin < GetBufferSize());
if (HasFX() && m_dwSliceBegin != m_dwSliceEnd) // Discontinuous buffer slices
m_fxChain->FxDiscontinuity(); // Inform effects of break in their input data
m_dwSliceEnd = (m_dwSliceBegin + dwBytes) % GetBufferSize();
// If this is a MIXIN buffer, write silence to the new slice
if (m_dsbd.dwFlags & DSBCAPS_MIXIN)
m_pDeviceBuffer->m_pSysMemBuffer->WriteSilence(m_dsbd.lpwfxFormat->wBitsPerSample, m_dwSliceBegin, m_dwSliceEnd);
}
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* MoveCurrentSlice
*
* Description:
* Shifts forward the audio buffer slice that is being processed.
*
* Arguments:
* DWORD [in]: Size in bytes for the new buffer slice.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::MoveCurrentSlice"
void CDirectSoundSecondaryBuffer::MoveCurrentSlice(DWORD dwBytes)
{
DPF_ENTER();
DPF_TIMING(DPFLVL_MOREINFO, "dwBytes=%lu (%s%s%sbuffer%s at 0x%p)", dwBytes,
m_dsbd.dwFlags & DSBCAPS_MIXIN ? TEXT("MIXIN ") : TEXT(""),
m_dsbd.dwFlags & DSBCAPS_SINKIN ? TEXT("SINKIN ") : TEXT(""),
!(m_dsbd.dwFlags & (DSBCAPS_MIXIN|DSBCAPS_SINKIN)) ? TEXT("regular ") : TEXT(""),
HasFX() ? TEXT(" w/effects") : TEXT(""), this);
ASSERT(dwBytes > 0 && dwBytes < GetBufferSize());
// Slide the current slice forwards and make it dwBytes wide
if (m_dwSliceBegin == MAX_DWORD) // FIXME: for debugging only
{
ASSERT(!"Unset processing slice detected");
m_playState = Stopped;
m_dwSliceBegin = m_dwSliceEnd = MAX_DWORD;
// FIXME: this code can disappear once all bugs are ironed out
}
else
{
m_dwSliceBegin = m_dwSliceEnd;
}
ASSERT(m_dwSliceBegin < GetBufferSize());
m_dwSliceEnd = (m_dwSliceBegin + dwBytes) % GetBufferSize();
// If this is a MIXIN buffer, write silence to the new slice
if (m_dsbd.dwFlags & DSBCAPS_MIXIN)
m_pDeviceBuffer->m_pSysMemBuffer->WriteSilence(m_dsbd.lpwfxFormat->wBitsPerSample, m_dwSliceBegin, m_dwSliceEnd);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* DirectLock
*
* Description:
* An abbreviation for the frequent operation of locking a region of
* our contained audio buffer.
*
* Arguments:
* DWORD [in]: Byte offset to where the lock begins in the buffer.
* DWORD [in]: Size, in bytes, of the portion of the buffer to lock.
* LPVOID* [out]: Returns the first part of the locked region.
* LPDWORD [out]: Returns the size in bytes of the first part.
* LPVOID* [out]: Returns the second part of the locked region.
* LPDWORD [out]: Returns the size in bytes of the second part.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::DirectLock"
HRESULT CDirectSoundSecondaryBuffer::DirectLock(DWORD dwPosition, DWORD dwSize, LPVOID* ppvPtr1, LPDWORD pdwSize1, LPVOID* ppvPtr2, LPDWORD pdwSize2)
{
DPF_ENTER();
ASSERT(m_pDeviceBuffer != NULL);
HRESULT hr = m_pDeviceBuffer->CRenderWaveBuffer::Lock(dwPosition, dwSize, ppvPtr1, pdwSize1, ppvPtr2, pdwSize2);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* DirectUnlock
*
* Description:
* An abbreviation for the frequent operation of unlocking a region of
* our contained audio buffer.
*
* Arguments:
* LPVOID [in]: pointer to the first block.
* DWORD [in]: size of the first block.
* LPVOID [in]: pointer to the second block.
* DWORD [in]: size of the second block.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::DirectUnlock"
HRESULT CDirectSoundSecondaryBuffer::DirectUnlock(LPVOID pvPtr1, DWORD dwSize1, LPVOID pvPtr2, DWORD dwSize2)
{
DPF_ENTER();
ASSERT(m_pDeviceBuffer != NULL);
HRESULT hr = m_pDeviceBuffer->CRenderWaveBuffer::Unlock(pvPtr1, dwSize1, pvPtr2, dwSize2);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* FindSendLoop
*
* Description:
* Auxiliary function used in effects.cpp to detect send loops.
* Returns DSERR_SENDLOOP if a send effect pointing to this buffer
* is detected anywhere in the send graph rooted at pCurBuffer.
*
* Arguments:
* CDirectSoundSecondaryBuffer* [in]: Current buffer in graph traversal.
*
* Returns:
* HRESULT: DirectSound/COM result code; DSERR_SENDLOOP if a send loop
* is found, otherwise DS_OK.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::FindSendLoop"
HRESULT CDirectSoundSecondaryBuffer::FindSendLoop(CDirectSoundSecondaryBuffer* pCurBuffer)
{
HRESULT hr = DS_OK;
DPF_ENTER();
CHECK_WRITE_PTR(pCurBuffer);
if (pCurBuffer == this)
{
RPF(DPFLVL_ERROR, "Send loop detected from buffer at 0x%p to itself", this);
hr = DSERR_SENDLOOP;
}
else if (pCurBuffer->HasFX())
{
// Buffer has effects - look for send effects and call ourself recursively.
for (CNode<CEffect*>* pFxNode = pCurBuffer->m_fxChain->m_fxList.GetListHead();
pFxNode && SUCCEEDED(hr);
pFxNode = pFxNode->m_pNext)
{
CDirectSoundSecondaryBuffer* pDstBuffer = pFxNode->m_data->GetDestBuffer();
if (pDstBuffer)
hr = FindSendLoop(pDstBuffer);
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* CalculateOffset
*
* Description:
* Given a CDirectSoundSecondaryBuffer and a byte offset into that
* buffer, calculates the "corresponding" byte offset in this buffer
* such that both buffers' play cursors will reach their respective
* offsets at the same time. To do this we need to know the exact
* difference between the buffers' play positions, which we obtain
* using a voting heuristic, since our underlying driver models
* (VxD, WDM) don't support this operation directly.
*
* Arguments:
* CDirectSoundSecondaryBuffer* [in]: Buffer to get offset from.
* DWORD [in]: Position in the buffer to which to synchronize.
* DWORD* [out]: Returns the corresponding position in this buffer.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::CalculateOffset"
// Our compiler doesn't allow this POSOFFSET type to be local to
// the function below, because it is used as a template argument.
struct POSOFFSET {LONG offset; int count; POSOFFSET(LONG _o =0) {offset=_o; count=1;}};
HRESULT CDirectSoundSecondaryBuffer::CalculateOffset(CDirectSoundSecondaryBuffer* pDsBuffer, DWORD dwTargetPos, DWORD* pdwSyncPos)
{
const int nMaxAttempts = 7; // Getting the cursor positions takes a surprisingly long time
const int nQuorum = 3; // How many "votes" are required to determine the offset
// Note: these arbitrary constants were found to result in an accurate
// offset calculation "almost always". An out-of-sync send is very easy
// to hear (it sound phasy and flangy); if we ever detect this problem in
// testing, this code should be revisited.
// Sanity checks
CHECK_WRITE_PTR(pDsBuffer);
CHECK_WRITE_PTR(pdwSyncPos);
ASSERT(dwTargetPos < pDsBuffer->GetBufferSize());
CList<POSOFFSET> lstOffsets; // List of cursor offsets found
CNode<POSOFFSET>* pCheckNode; // Used to check AddNoteToList failures
DWORD dwFirstPos1 = 0, dwFirstPos2 = 0; // First cursor positions found
DWORD dwPos1, dwPos2; // Current cursor positions found
LONG lOffset; // Current offset
BOOL fOffsetFound = FALSE; // Found the best offset?
int nOurBlockSize = Format()->nBlockAlign; // Used for brevity below
int nBufferBlockSize = pDsBuffer->Format()->nBlockAlign; // Ditto
HRESULT hr = DS_OK;
DPF_ENTER();
// Uncomment this to see how long this function takes to run
// DWORD dwTimeBefore = timeGetTime();
for (int i=0; i<nMaxAttempts && SUCCEEDED(hr); ++i)
{
hr = GetInternalCursors(&dwPos1, NULL);
if (SUCCEEDED(hr))
hr = pDsBuffer->GetInternalCursors(&dwPos2, NULL);
if (SUCCEEDED(hr))
{
// Save the first buffer positions found
if (i == 0)
dwFirstPos1 = dwPos1, dwFirstPos2 = dwPos2;
// If we detect a cursor wraparound, start all over again [??]
if (dwPos1 < dwFirstPos1 || dwPos2 < dwFirstPos2)
{
#ifdef ENABLE_SENDS // Debug output for later debugging
for (int j=0; j<5; ++j)
{
DPF(DPFLVL_INFO, "Take %d: dwPos1=%d < dwFirstPos1=%d || dwPos2=%d < dwFirstPos2=%d", i, dwPos1, dwFirstPos1, dwPos2, dwFirstPos2);
Sleep(10); GetInternalCursors(&dwPos1, NULL); pDsBuffer->GetInternalCursors(&dwPos2, NULL);
}
#endif
break;
}
// Convert dwPos2 from pDsBuffer's sample block units into ours
dwPos2 = dwPos2 * nOurBlockSize / nBufferBlockSize;
LONG lNewOffset = dwPos2 - dwPos1;
DPF_TIMING(DPFLVL_INFO, "Play offset #%d = %ld", i, lNewOffset);
for (CNode<POSOFFSET>* pOff = lstOffsets.GetListHead(); pOff; pOff = pOff->m_pNext)
if (pOff->m_data.offset >= lNewOffset - nOurBlockSize &&
pOff->m_data.offset <= lNewOffset + nOurBlockSize)
{ // I.e. if the offsets are equal or only off by 1 sample block
++pOff->m_data.count;
break;
}
if (pOff == NULL) // A new offset was found - add it to the list
{
pCheckNode = lstOffsets.AddNodeToList(POSOFFSET(lNewOffset));
ASSERT(pCheckNode != NULL);
}
else if (pOff->m_data.count == nQuorum) // We have a winner!
{
lOffset = pOff->m_data.offset;
fOffsetFound = TRUE;
#ifdef ENABLE_SENDS // Debug output for later debugging
DPF(DPFLVL_INFO, "QUORUM REACHED");
#endif
break;
}
}
}
if (SUCCEEDED(hr) && !fOffsetFound) // Didn't get enough votes for any one offset
{
// Just pick the one with the most "votes"
int nBestSoFar = 0;
for (CNode<POSOFFSET>* pOff = lstOffsets.GetListHead(); pOff; pOff = pOff->m_pNext)
if (pOff->m_data.count > nBestSoFar)
{
lOffset = pOff->m_data.offset;
nBestSoFar = pOff->m_data.count;
}
ASSERT(nBestSoFar > 0);
}
if (SUCCEEDED(hr))
{
// If dwTargetPos is smaller than the play position on pDsBuffer, it must have
// wrapped around, so we put it back where it would be if it hadn't wrapped
if (dwTargetPos < dwFirstPos2)
dwTargetPos += pDsBuffer->GetBufferSize();
// Convert dwTargetPos from pDsBuffer's sample block units into ours
dwTargetPos = dwTargetPos * nOurBlockSize / nBufferBlockSize;
#ifdef DEBUG_TIMING
if (dwTargetPos - dwFirstPos2*nOurBlockSize/nBufferBlockSize > GetBufferSize())
ASSERT(!"Sync buffer's target and play positions are further apart than our buffer size");
#endif
// And finally...
*pdwSyncPos = dwTargetPos - lOffset;
if (*pdwSyncPos >= GetBufferSize())
{
*pdwSyncPos -= GetBufferSize();
ASSERT(*pdwSyncPos < GetBufferSize());
}
DPF_TIMING(DPFLVL_INFO, "Target buffer size=%lu, play pos=%lu, target pos=%lu", pDsBuffer->GetBufferSize(), dwFirstPos2, dwTargetPos);
DPF_TIMING(DPFLVL_INFO, "Source buffer size=%lu, play pos=%lu, sync pos=%lu", GetBufferSize(), dwFirstPos1, *pdwSyncPos);
}
// Uncomment this to see how long this function takes to run
// DWORD dwTimeAfter = timeGetTime();
// DPF(DPFLVL_MOREINFO, "Calculations took %ld ms", dwTimeAfter-dwTimeBefore);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SynchronizeToBuffer
*
* Description:
* Synchronizes this buffer's current processing slice to that of the
* buffer passed in as an argument.
*
* Arguments:
* CDirectSoundSecondaryBuffer* [in]: Buffer to synchronize to.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SynchronizeToBuffer"
void CDirectSoundSecondaryBuffer::SynchronizeToBuffer(CDirectSoundSecondaryBuffer* pSyncBuffer)
{
DPF_ENTER();
DWORD dwSliceBegin, dwSliceEnd, dwSliceSize;
pSyncBuffer->GetCurrentSlice(&dwSliceBegin, &dwSliceEnd);
dwSliceSize = DISTANCE(dwSliceBegin, dwSliceEnd, pSyncBuffer->GetBufferSize());
// Convert dwSliceSize from pSyncBuffer's sample block units into ours
dwSliceSize = dwSliceSize * Format()->nBlockAlign / pSyncBuffer->Format()->nBlockAlign;
// Convert dwSliceBegin into an offset into our buffer (taking into
// account the relative play cursors of our buffer and pSyncBuffer)
CalculateOffset(pSyncBuffer, dwSliceBegin, &dwSliceBegin);
// Establish our new processing slice
SetCurrentSlice(dwSliceBegin, dwSliceSize);
// No point propagating an error to our caller, which is the streaming thread;
// CalculateOffset() can only fail if GetCurrentPosition() fails, in which case
// everything will come to a grinding halt soon enough anyway.
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* UpdatePlayState
*
* Description:
* Auxiliary function used by the streaming thread to update this
* buffer's playing state. This is called once per buffer when the
* effects/streaming thread begins a processing pass; then for the
* rest of the pass, individual effects can query our state using
* GetPlayState(), without needing to call GetState() repeatedly
* on our device buffer.
*
* Arguments:
* (void)
*
* Returns:
* (void) - If GetState() fails, we simply set our state to FALSE.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::UpdatePlayState"
DSPLAYSTATE CDirectSoundSecondaryBuffer::UpdatePlayState(void)
{
DSPLAYSTATE oldPlayState = m_playState;
DWORD dwState;
DPF_ENTER();
if (SUCCEEDED(m_pDeviceBuffer->GetState(&dwState)))
{
if (dwState & VAD_BUFFERSTATE_STARTED)
if (m_playState <= Playing)
m_playState = Playing;
else
m_playState = Starting;
else
if (m_playState >= Stopping)
m_playState = Stopped;
else
m_playState = Stopping;
}
else
{
DPF(DPFLVL_ERROR, "Cataclysmic GetState() failure");
m_playState = Stopped;
}
if (oldPlayState != m_playState)
{
static TCHAR* szStates[] = {TEXT("Starting"), TEXT("Playing"), TEXT("Stopping"), TEXT("Stopped")};
DPF(DPFLVL_MOREINFO, "Buffer at 0x%p went from %s to %s", this, szStates[oldPlayState], szStates[m_playState]);
}
DPF_LEAVE(m_playState);
return m_playState;
}
/***************************************************************************
*
* SetInitialSlice
*
* Description:
* Auxiliary function used by the streaming thread to establish an
* initial processing slice for this buffer when it starts playing.
* We try to synchronize with an active buffer that is sending to us,
* and if none are available we start at our current write cursor.
*
* Arguments:
* REFERENCE_TIME [in]: Size of processing slice to be established.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetInitialSlice"
void CDirectSoundSecondaryBuffer::SetInitialSlice(REFERENCE_TIME rtSliceSize)
{
DPF_ENTER();
if (GetPlayState() == Starting && !(GetBufferType() & DSBCAPS_SINKIN))
{
CNode<CDirectSoundSecondaryBuffer*>* pSender;
for (pSender = m_lstSenders.GetListHead(); pSender; pSender = pSender->m_pNext)
if (pSender->m_data->IsPlaying())
{
// Found an active buffer sending to us
DPF_TIMING(DPFLVL_INFO, "Synchronizing MIXIN buffer at 0x%p with send buffer at 0x%p", this, pSender->m_data);
SynchronizeToBuffer(pSender->m_data);
break;
}
if (pSender == NULL)
{
DPF_TIMING(DPFLVL_INFO, "No active buffers found sending to MIXIN buffer at 0x%p", this);
SetCurrentSlice(CURRENT_WRITE_POS, RefTimeToBytes(rtSliceSize, Format()));
}
}
DPF_LEAVE_VOID();
}
#ifdef FUTURE_MULTIPAN_SUPPORT
/***************************************************************************
*
* SetChannelVolume
*
* Description:
* Sets the volume on a set of output channels for a given mono buffer.
*
* Arguments:
* [MISSING]
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBuffer::SetChannelVolume"
HRESULT CDirectSoundSecondaryBuffer::SetChannelVolume(DWORD dwChannelCount, LPDWORD pdwChannels, LPLONG plVolumes)
{
HRESULT hr = DS_OK;
BOOL fChanged = FALSE;
DPF_ENTER();
// Check access rights
if(!(m_dsbd.dwFlags & DSBCAPS_CTRLCHANNELVOLUME))
{
RPF(DPFLVL_ERROR, "Buffer does not have CTRLCHANNELVOLUME");
hr = DSERR_CONTROLUNAVAIL;
}
// Check if channel levels have changed
if(SUCCEEDED(hr))
{
if (dwChannelCount != m_dwChannelCount)
fChanged = TRUE;
else for (DWORD i=0; i<dwChannelCount && !fChanged; ++i)
if (pdwChannels[i] != m_pdwChannels[i] || plVolumes[i] != m_plChannelVolumes[i])
fChanged = TRUE;
}
// Set channel volumes if they've changed
if(SUCCEEDED(hr) && fChanged)
{
hr = m_pDeviceBuffer->SetChannelAttenuations(m_lVolume, dwChannelCount, pdwChannels, plVolumes);
// Update our local copy if successful
if(SUCCEEDED(hr))
{
MEMFREE(m_pdwChannels);
MEMFREE(m_plChannelVolumes);
m_pdwChannels = MEMALLOC_A(DWORD, dwChannelCount);
hr = HRFROMP(m_pdwChannels);
}
if (SUCCEEDED(hr))
{
m_plChannelVolumes = MEMALLOC_A(LONG, dwChannelCount);
hr = HRFROMP(m_plChannelVolumes);
}
if (SUCCEEDED(hr))
{
CopyMemory(m_pdwChannels, pdwChannels, sizeof(DWORD) * dwChannelCount);
CopyMemory(m_plChannelVolumes, plVolumes, sizeof(LONG) * dwChannelCount);
m_dwChannelCount = dwChannelCount;
}
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
#endif // FUTURE_MULTIPAN_SUPPORT
/***************************************************************************
*
* CDirectSound3dListener
*
* Description:
* Object constructor.
*
* Arguments:
* CUnknown * [in]: parent object.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::CDirectSound3dListener"
CDirectSound3dListener::CDirectSound3dListener(CDirectSoundPrimaryBuffer *pParent)
{
DPF_ENTER();
DPF_CONSTRUCT(CDirectSound3dListener);
// Initialize defaults
m_pParent = pParent;
m_pImpDirectSound3dListener = NULL;
m_pDevice3dListener = NULL;
m_hrInit = DSERR_UNINITIALIZED;
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* ~CDirectSound3dListener
*
* Description:
* Object destructor.
*
* Arguments:
* (void)
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::~CDirectSound3dListener"
CDirectSound3dListener::~CDirectSound3dListener(void)
{
DPF_ENTER();
DPF_DESTRUCT(CDirectSound3dListener);
// Free 3D listener object
RELEASE(m_pDevice3dListener);
// Free interface(s)
DELETE(m_pImpDirectSound3dListener);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* Initialize
*
* Description:
* Initializes the object. If this function fails, the object should
* be immediately deleted.
*
* Arguments:
* CPrimaryRenderWaveBuffer * [in]: device buffer.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::Initialize"
HRESULT CDirectSound3dListener::Initialize(CPrimaryRenderWaveBuffer *pDeviceBuffer)
{
HRESULT hr;
DPF_ENTER();
// Create the device 3D listener
hr = pDeviceBuffer->Create3dListener(&m_pDevice3dListener);
// Create the 3D listener interfaces
if(SUCCEEDED(hr))
{
hr = CreateAndRegisterInterface(m_pParent, IID_IDirectSound3DListener, this, &m_pImpDirectSound3dListener);
}
// Success
if(SUCCEEDED(hr))
{
m_hrInit = DS_OK;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetAllParameters
*
* Description:
* Gets all listener properties.
*
* Arguments:
* LPDS3DLISTENER [out]: receives properties.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::GetAllParameters"
HRESULT CDirectSound3dListener::GetAllParameters(LPDS3DLISTENER pParam)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->GetAllParameters(pParam);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetDistanceFactor
*
* Description:
* Gets the world's distance factor.
*
* Arguments:
* D3DVALUE* [out]: receives distance factor.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::GetDistanceFactor"
HRESULT CDirectSound3dListener::GetDistanceFactor(D3DVALUE* pflDistanceFactor)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->GetDistanceFactor(pflDistanceFactor);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetDopplerFactor
*
* Description:
* Gets the world's doppler factor.
*
* Arguments:
* D3DVALUE* [out]: receives doppler factor.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::GetDopplerFactor"
HRESULT CDirectSound3dListener::GetDopplerFactor(D3DVALUE* pflDopplerFactor)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->GetDopplerFactor(pflDopplerFactor);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetOrientation
*
* Description:
* Gets the listener's orientation.
*
* Arguments:
* D3DVECTOR* [out]: receives front orientation.
* D3DVECTOR* [out]: receives top orientation.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::GetOrientation"
HRESULT CDirectSound3dListener::GetOrientation(D3DVECTOR* pvrOrientationFront, D3DVECTOR* pvrOrientationTop)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->GetOrientation(pvrOrientationFront, pvrOrientationTop);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetPosition
*
* Description:
* Gets the listener's position.
*
* Arguments:
* D3DVECTOR* [out]: receives position.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::GetPosition"
HRESULT CDirectSound3dListener::GetPosition(D3DVECTOR* pvrPosition)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->GetPosition(pvrPosition);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetRolloffFactor
*
* Description:
* Gets the world's rolloff factor.
*
* Arguments:
* D3DVALUE* [out]: receives rolloff factor.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::GetRolloffFactor"
HRESULT CDirectSound3dListener::GetRolloffFactor(D3DVALUE* pflRolloffFactor)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->GetRolloffFactor(pflRolloffFactor);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetVelocity
*
* Description:
* Gets the listener's velocity.
*
* Arguments:
* D3DVECTOR* [out]: receives velocity.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::GetVelocity"
HRESULT CDirectSound3dListener::GetVelocity(D3DVECTOR* pvrVelocity)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->GetVelocity(pvrVelocity);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetAllParameters
*
* Description:
* Sets all listener properties.
*
* Arguments:
* LPDS3DLISTENER [in]: properties.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetAllParameters"
HRESULT CDirectSound3dListener::SetAllParameters(LPCDS3DLISTENER pParam, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetAllParameters(pParam, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetDistanceFactor
*
* Description:
* Sets the world's distance factor.
*
* Arguments:
* D3DVALUE [in]: distance factor.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetDistanceFactor"
HRESULT CDirectSound3dListener::SetDistanceFactor(D3DVALUE flDistanceFactor, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetDistanceFactor(flDistanceFactor, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetDopplerFactor
*
* Description:
* Sets the world's Doppler factor.
*
* Arguments:
* D3DVALUE [in]: Doppler factor.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetDopplerFactor"
HRESULT CDirectSound3dListener::SetDopplerFactor(D3DVALUE flDopplerFactor, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetDopplerFactor(flDopplerFactor, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetOrientation
*
* Description:
* Sets the listener's orientation.
*
* Arguments:
* REFD3DVECTOR [in]: front orientation.
* REFD3DVECTOR [in]: top orientation.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetOrientation"
HRESULT CDirectSound3dListener::SetOrientation(REFD3DVECTOR vrOrientationFront, REFD3DVECTOR vrOrientationTop, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetOrientation(vrOrientationFront, vrOrientationTop, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetPosition
*
* Description:
* Sets the listener's position.
*
* Arguments:
* REFD3DVECTOR [in]: position.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetPosition"
HRESULT CDirectSound3dListener::SetPosition(REFD3DVECTOR vrPosition, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetPosition(vrPosition, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetRolloffFactor
*
* Description:
* Sets the world's rolloff factor.
*
* Arguments:
* D3DVALUE [in]: rolloff factor.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetRolloffFactor"
HRESULT CDirectSound3dListener::SetRolloffFactor(D3DVALUE flRolloffFactor, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetRolloffFactor(flRolloffFactor, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetVelocity
*
* Description:
* Sets the listener's velocity.
*
* Arguments:
* REFD3DVECTOR [in]: velocity.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetVelocity"
HRESULT CDirectSound3dListener::SetVelocity(REFD3DVECTOR vrVelocity, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetVelocity(vrVelocity, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* CommitDeferredSettings
*
* Description:
* Commits deferred settings.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::CommitDeferredSettings"
HRESULT CDirectSound3dListener::CommitDeferredSettings(void)
{
HRESULT hr;
DPF_ENTER();
// Commit all listener settings
hr = m_pDevice3dListener->CommitDeferred();
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetSpeakerConfig
*
* Description:
* Sets device speaker configuration.
*
* Arguments:
* DWORD [in]: speaker configuration.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dListener::SetSpeakerConfig"
HRESULT CDirectSound3dListener::SetSpeakerConfig(DWORD dwSpeakerConfig)
{
HRESULT hr;
DPF_ENTER();
hr = m_pDevice3dListener->SetSpeakerConfig(dwSpeakerConfig);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* CDirectSound3dBuffer
*
* Description:
* Object constructor.
*
* Arguments:
* CUnknown * [in]: parent object.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::CDirectSound3dBuffer"
CDirectSound3dBuffer::CDirectSound3dBuffer(CDirectSoundSecondaryBuffer *pParent)
{
DPF_ENTER();
DPF_CONSTRUCT(CDirectSound3dBuffer);
// Initialize defaults
m_pParent = pParent;
m_pImpDirectSound3dBuffer = NULL;
m_pWrapper3dObject = NULL;
m_pDevice3dObject = NULL;
m_hrInit = DSERR_UNINITIALIZED;
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* ~CDirectSound3dBuffer
*
* Description:
* Object destructor.
*
* Arguments:
* (void)
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::~CDirectSound3dBuffer"
CDirectSound3dBuffer::~CDirectSound3dBuffer(void)
{
DPF_ENTER();
DPF_DESTRUCT(CDirectSound3dBuffer);
// Free 3D buffer objects
RELEASE(m_pWrapper3dObject);
RELEASE(m_pDevice3dObject);
// Free all interfaces
DELETE(m_pImpDirectSound3dBuffer);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* Initialize
*
* Description:
* Initializes a buffer object. If this function fails, the object
* should be immediately deleted.
*
* Arguments:
* REFGUID [in]: 3D algorithm identifier.
* DWORD [in]: buffer creation flags.
* DWORD [in]: buffer frequency.
* CDirectSound3dListener * [in]: listener object.
* CDirectSound3dBuffer * [in]: source object to duplicate from.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::Initialize"
HRESULT CDirectSound3dBuffer::Initialize(REFGUID guid3dAlgorithm, DWORD dwFlags, DWORD dwFrequency, CDirectSound3dListener *pListener, CDirectSound3dBuffer *pSource)
{
const BOOL fMute3dAtMaxDistance = MAKEBOOL(dwFlags & DSBCAPS_MUTE3DATMAXDISTANCE);
const BOOL fDopplerEnabled = !MAKEBOOL((dwFlags & DSBCAPS_CTRLFX) && !(dwFlags & DSBCAPS_SINKIN));
DS3DBUFFER param;
HRESULT hr;
DPF_ENTER();
// Create the wrapper 3D object
m_pWrapper3dObject = NEW(CWrapper3dObject(pListener->m_pDevice3dListener, guid3dAlgorithm, fMute3dAtMaxDistance, fDopplerEnabled, dwFrequency));
hr = HRFROMP(m_pWrapper3dObject);
// Copy the source buffer's 3D properties
if(SUCCEEDED(hr) && pSource)
{
InitStruct(¶m, sizeof(param));
hr = pSource->GetAllParameters(¶m);
if(SUCCEEDED(hr))
{
hr = SetAllParameters(¶m, 0);
}
}
// Register the 3D buffer interfaces
if(SUCCEEDED(hr))
{
hr = CreateAndRegisterInterface(m_pParent, IID_IDirectSound3DBuffer, this, &m_pImpDirectSound3dBuffer);
}
if(SUCCEEDED(hr))
{
hr = m_pParent->RegisterInterface(IID_IDirectSound3DBufferPrivate, m_pImpDirectSound3dBuffer, (IDirectSound3DBufferPrivate*)m_pImpDirectSound3dBuffer);
}
// Success
if(SUCCEEDED(hr))
{
m_hrInit = DS_OK;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* AcquireResources
*
* Description:
* Acquires hardware resources.
*
* Arguments:
* CSecondaryRenderWaveBuffer * [in]: device buffer.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::AcquireResources"
HRESULT CDirectSound3dBuffer::AcquireResources(CSecondaryRenderWaveBuffer *pDeviceBuffer)
{
HRESULT hr;
DPF_ENTER();
// Create the device 3D object
hr = pDeviceBuffer->Create3dObject(m_pWrapper3dObject->GetListener(), &m_pDevice3dObject);
if(SUCCEEDED(hr))
{
hr = m_pWrapper3dObject->SetObjectPointer(m_pDevice3dObject);
}
if(SUCCEEDED(hr))
{
DPF(DPFLVL_MOREINFO, "3D buffer at 0x%p has acquired resources at 0x%p", this, m_pDevice3dObject);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* FreeResources
*
* Description:
* Frees hardware resources.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::FreeResources"
HRESULT CDirectSound3dBuffer::FreeResources(void)
{
HRESULT hr;
DPF_ENTER();
// Free the device 3D object
hr = m_pWrapper3dObject->SetObjectPointer(NULL);
if(SUCCEEDED(hr))
{
RELEASE(m_pDevice3dObject);
DPF(DPFLVL_MOREINFO, "3D buffer at 0x%p has freed its resources", this);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetAttenuation
*
* Description:
* Sets the attenuation for a given buffer. This function is
* overridden in the 3D buffer because the 3D object may need
* notification.
*
* Arguments:
* PDSVOLUMEPAN [in]: new attenuation.
* LPBOOL [out]: receives TRUE if the device buffer should be notified
* of the change.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetAttenuation"
HRESULT CDirectSound3dBuffer::SetAttenuation(PDSVOLUMEPAN pdsvp, LPBOOL pfContinue)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetAttenuation(pdsvp, pfContinue);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetFrequency
*
* Description:
* Sets the frequency for a given buffer. This function is
* overridden in the 3D buffer because the 3D object may need
* notification.
*
* Arguments:
* DWORD [in]: new frequency.
* LPBOOL [out]: receives TRUE if the device buffer should be notified
* of the change.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetFrequency"
HRESULT CDirectSound3dBuffer::SetFrequency(DWORD dwFrequency, LPBOOL pfContinue)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetFrequency(dwFrequency, pfContinue);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetMute
*
* Description:
* Sets the mute status for a given buffer. This function is
* overridden in the 3D buffer because the 3D object may need
* notification.
*
* Arguments:
* BOOL [in]: new mute status.
* LPBOOL [out]: receives TRUE if the device buffer should be notified
* of the change.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetMute"
HRESULT CDirectSound3dBuffer::SetMute(BOOL fMute, LPBOOL pfContinue)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetMute(fMute, pfContinue);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetAllParameters
*
* Description:
* Retrieves all 3D properties for the buffer.
*
* Arguments:
* LPDS3DBUFFER [out]: recieves properties.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetAllParameters"
HRESULT CDirectSound3dBuffer::GetAllParameters(LPDS3DBUFFER pParam)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetAllParameters(pParam);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetConeAngles
*
* Description:
* Gets inside and outside cone angles.
*
* Arguments:
* LPDWORD [out]: receives inside cone angle.
* LPDWORD [out]: receives outside cone angle.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetConeAngles"
HRESULT CDirectSound3dBuffer::GetConeAngles(LPDWORD pdwInside, LPDWORD pdwOutside)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetConeAngles(pdwInside, pdwOutside);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetConeOrientation
*
* Description:
* Gets cone orienation.
*
* Arguments:
* D3DVECTOR* [out]: receives cone orientation.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetConeOrientation"
HRESULT CDirectSound3dBuffer::GetConeOrientation(D3DVECTOR* pvrConeOrientation)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetConeOrientation(pvrConeOrientation);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetConeOutsideVolume
*
* Description:
* Gets cone orienation.
*
* Arguments:
* LPLONG [out]: receives volume.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetConeOutsideVolume"
HRESULT CDirectSound3dBuffer::GetConeOutsideVolume(LPLONG plVolume)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetConeOutsideVolume(plVolume);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetMaxDistance
*
* Description:
* Gets the object's maximum distance from the listener.
*
* Arguments:
* D3DVALUE* [out]: receives max distance.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetMaxDistance"
HRESULT CDirectSound3dBuffer::GetMaxDistance(D3DVALUE* pflMaxDistance)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetMaxDistance(pflMaxDistance);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetMinDistance
*
* Description:
* Gets the object's minimim distance from the listener.
*
* Arguments:
* D3DVALUE* [out]: receives min distance.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetMinDistance"
HRESULT CDirectSound3dBuffer::GetMinDistance(D3DVALUE* pflMinDistance)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetMinDistance(pflMinDistance);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetMode
*
* Description:
* Gets the object's mode.
*
* Arguments:
* LPDWORD [out]: receives mode.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetMode"
HRESULT CDirectSound3dBuffer::GetMode(LPDWORD pdwMode)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetMode(pdwMode);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetPosition
*
* Description:
* Gets the object's position.
*
* Arguments:
* D3DVECTOR* [out]: receives position.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetPosition"
HRESULT CDirectSound3dBuffer::GetPosition(D3DVECTOR* pvrPosition)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetPosition(pvrPosition);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetVelocity
*
* Description:
* Gets the object's velocity.
*
* Arguments:
* D3DVECTOR* [out]: receives velocity.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetVelocity"
HRESULT CDirectSound3dBuffer::GetVelocity(D3DVECTOR* pvrVelocity)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->GetVelocity(pvrVelocity);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetAllParameters
*
* Description:
* Sets all object properties.
*
* Arguments:
* LPDS3DBUFFER [in]: object parameters.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetAllParameters"
HRESULT CDirectSound3dBuffer::SetAllParameters(LPCDS3DBUFFER pParam, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetAllParameters(pParam, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetConeAngles
*
* Description:
* Sets the sound cone's angles.
*
* Arguments:
* DWORD [in]: inside angle.
* DWORD [in]: outside angle.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetConeAngles"
HRESULT CDirectSound3dBuffer::SetConeAngles(DWORD dwInside, DWORD dwOutside, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetConeAngles(dwInside, dwOutside, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetConeOrientation
*
* Description:
* Sets the sound cone's orientation.
*
* Arguments:
* REFD3DVECTOR [in]: orientation.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetConeOrientation"
HRESULT CDirectSound3dBuffer::SetConeOrientation(REFD3DVECTOR vrOrientation, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetConeOrientation(vrOrientation, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetConeOutsideVolume
*
* Description:
* Sets the sound cone's outside volume.
*
* Arguments:
* LONG [in]: volume.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetConeOutsideVolume"
HRESULT CDirectSound3dBuffer::SetConeOutsideVolume(LONG lVolume, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetConeOutsideVolume(lVolume, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetMaxDistance
*
* Description:
* Sets the objects maximum distance from the listener.
*
* Arguments:
* D3DVALUE [in]: maximum distance.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetMaxDistance"
HRESULT CDirectSound3dBuffer::SetMaxDistance(D3DVALUE flMaxDistance, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetMaxDistance(flMaxDistance, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetMinDistance
*
* Description:
* Sets the objects minimum distance from the listener.
*
* Arguments:
* D3DVALUE [in]: minimum distance.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetMinDistance"
HRESULT CDirectSound3dBuffer::SetMinDistance(D3DVALUE flMinDistance, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetMinDistance(flMinDistance, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetMode
*
* Description:
* Sets the objects mode.
*
* Arguments:
* DWORD [in]: mode.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetMode"
HRESULT CDirectSound3dBuffer::SetMode(DWORD dwMode, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetMode(dwMode, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetPosition
*
* Description:
* Sets the objects position.
*
* Arguments:
* REFD3DVECTOR [in]: position.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetPosition"
HRESULT CDirectSound3dBuffer::SetPosition(REFD3DVECTOR vrPosition, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetPosition(vrPosition, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetVelocity
*
* Description:
* Sets the objects velocity.
*
* Arguments:
* REFD3DVECTOR [in]: velocity.
* DWORD [in]: flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::SetVelocity"
HRESULT CDirectSound3dBuffer::SetVelocity(REFD3DVECTOR vrVelocity, DWORD dwFlags)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapper3dObject->SetVelocity(vrVelocity, !(dwFlags & DS3D_DEFERRED));
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetAttenuation
*
* Description:
* Obtains the buffer's current true attenuation (as opposed to
* GetVolume, which just returns the last volume set by the app).
*
* Arguments:
* FLOAT* [out]: attenuation in millibels.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSound3dBuffer::GetAttenuation"
HRESULT CDirectSound3dBuffer::GetAttenuation(FLOAT* pfAttenuation)
{
DPF_ENTER();
HRESULT hr = m_pParent->GetAttenuation(pfAttenuation);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* CDirectSoundPropertySet
*
* Description:
* Object constructor.
*
* Arguments:
* CUnknown * [in]: parent object.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::CDirectSoundPropertySet"
CDirectSoundPropertySet::CDirectSoundPropertySet(CUnknown *pParent)
{
DPF_ENTER();
DPF_CONSTRUCT(CDirectSoundPropertySet);
// Set defaults
m_pParent = pParent;
m_pImpKsPropertySet = NULL;
m_pWrapperPropertySet = NULL;
m_pDevicePropertySet = NULL;
m_hrInit = DSERR_UNINITIALIZED;
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* ~CDirectSoundPropertySet
*
* Description:
* Object destructor.
*
* Arguments:
* (void)
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::~CDirectSoundPropertySet"
CDirectSoundPropertySet::~CDirectSoundPropertySet(void)
{
DPF_ENTER();
DPF_DESTRUCT(CDirectSoundPropertySet);
// Free property set objects
RELEASE(m_pWrapperPropertySet);
RELEASE(m_pDevicePropertySet);
// Free interface(s)
DELETE(m_pImpKsPropertySet);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* Initialize
*
* Description:
* Initializes the object.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::Initialize"
HRESULT CDirectSoundPropertySet::Initialize(void)
{
HRESULT hr;
DPF_ENTER();
// Create the wrapper property set object
m_pWrapperPropertySet = NEW(CWrapperPropertySet);
hr = HRFROMP(m_pWrapperPropertySet);
// Register interface
if(SUCCEEDED(hr))
{
hr = CreateAndRegisterInterface(m_pParent, IID_IKsPropertySet, this, &m_pImpKsPropertySet);
}
// Success
if(SUCCEEDED(hr))
{
m_hrInit = DS_OK;
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* AcquireResources
*
* Description:
* Acquires hardware resources.
*
* Arguments:
* CRenderWaveBuffer * [in]: device buffer.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::AcquireResources"
HRESULT CDirectSoundPropertySet::AcquireResources(CRenderWaveBuffer *pDeviceBuffer)
{
HRESULT hr;
DPF_ENTER();
// Create the device property set object
ASSERT(m_pDevicePropertySet == NULL);
hr = pDeviceBuffer->CreatePropertySet(&m_pDevicePropertySet);
if(SUCCEEDED(hr))
{
hr = m_pWrapperPropertySet->SetObjectPointer(m_pDevicePropertySet);
}
if(SUCCEEDED(hr))
{
DPF(DPFLVL_MOREINFO, "Property set at 0x%p has acquired resources at 0x%p", this, m_pDevicePropertySet);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* FreeResources
*
* Description:
* Frees hardware resources.
*
* Arguments:
* (void)
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::FreeResources"
HRESULT CDirectSoundPropertySet::FreeResources(void)
{
HRESULT hr;
DPF_ENTER();
// Free the device property set object
hr = m_pWrapperPropertySet->SetObjectPointer(NULL);
if(SUCCEEDED(hr))
{
RELEASE(m_pDevicePropertySet);
DPF(DPFLVL_MOREINFO, "Property set at 0x%p has freed its resources", this);
}
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* QuerySupport
*
* Description:
* Queries for support of a given property set or property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id, or 0 to query for support of the property
* set as a whole.
* PULONG [out]: receives support flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::QuerySupport"
HRESULT CDirectSoundPropertySet::QuerySupport(REFGUID guidPropertySetId, ULONG ulPropertyId, PULONG pulSupport)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapperPropertySet->QuerySupport(guidPropertySetId, ulPropertyId, pulSupport);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetProperty
*
* Description:
* Gets data for a given property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id.
* LPVOID [in]: property parameters.
* ULONG [in]: size of property parameters.
* LPVOID [out]: receives property data.
* PULONG [in/out]: size of property data.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::GetProperty"
HRESULT CDirectSoundPropertySet::GetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, PULONG pcbPropertyData)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapperPropertySet->GetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, pcbPropertyData);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetProperty
*
* Description:
* Sets data for a given property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id.
* LPVOID [in]: property parameters.
* ULONG [in]: size of property parameters.
* LPVOID [in]: property data.
* ULONG [in]: size of property data.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundPropertySet::SetProperty"
HRESULT CDirectSoundPropertySet::SetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, ULONG cbPropertyData)
{
HRESULT hr;
DPF_ENTER();
hr = m_pWrapperPropertySet->SetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, cbPropertyData);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* CDirectSoundSecondaryBufferPropertySet
*
* Description:
* Object constructor.
*
* Arguments:
* CDirectSoundSecondaryBuffer * [in]: parent object.
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::CDirectSoundSecondaryBufferPropertySet"
CDirectSoundSecondaryBufferPropertySet::CDirectSoundSecondaryBufferPropertySet(CDirectSoundSecondaryBuffer *pParent)
: CDirectSoundPropertySet(pParent)
{
DPF_ENTER();
DPF_CONSTRUCT(CDirectSoundSecondaryBufferPropertySet);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* ~CDirectSoundSecondaryBufferPropertySet
*
* Description:
* Object destructor.
*
* Arguments:
* (void)
*
* Returns:
* (void)
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::~CDirectSoundSecondaryBufferPropertySet"
CDirectSoundSecondaryBufferPropertySet::~CDirectSoundSecondaryBufferPropertySet(void)
{
DPF_ENTER();
DPF_DESTRUCT(CDirectSoundSecondaryBufferPropertySet);
DPF_LEAVE_VOID();
}
/***************************************************************************
*
* QuerySupport
*
* Description:
* Queries for support of a given property set or property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id, or 0 to query for support of the property
* set as a whole.
* PULONG [out]: receives support flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::QuerySupport"
HRESULT CDirectSoundSecondaryBufferPropertySet::QuerySupport(REFGUID guidPropertySetId, ULONG ulPropertyId, PULONG pulSupport)
{
HRESULT hr;
DPF_ENTER();
hr = CPropertySetHandler::QuerySupport(guidPropertySetId, ulPropertyId, pulSupport);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* GetProperty
*
* Description:
* Gets data for a given property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id.
* LPVOID [in]: property parameters.
* ULONG [in]: size of property parameters.
* LPVOID [out]: receives property data.
* PULONG [in/out]: size of property data.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::GetProperty"
HRESULT CDirectSoundSecondaryBufferPropertySet::GetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, PULONG pcbPropertyData)
{
HRESULT hr;
DPF_ENTER();
hr = CPropertySetHandler::GetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, pcbPropertyData);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* SetProperty
*
* Description:
* Sets data for a given property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id.
* LPVOID [in]: property parameters.
* ULONG [in]: size of property parameters.
* LPVOID [in]: property data.
* ULONG [in]: size of property data.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::SetProperty"
HRESULT CDirectSoundSecondaryBufferPropertySet::SetProperty(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, ULONG cbPropertyData)
{
HRESULT hr;
DPF_ENTER();
hr = CPropertySetHandler::SetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, cbPropertyData);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* UnsupportedQueryHandler
*
* Description:
* Queries for support of a given property set or property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id, or 0 to query for support of the property
* set as a whole.
* PULONG [out]: receives support flags.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::UnsupportedQueryHandler"
HRESULT CDirectSoundSecondaryBufferPropertySet::UnsupportedQueryHandler(REFGUID guidPropertySetId, ULONG ulPropertyId, PULONG pulSupport)
{
HRESULT hr;
DPF_ENTER();
hr = CDirectSoundPropertySet::QuerySupport(guidPropertySetId, ulPropertyId, pulSupport);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* UnsupportedGetHandler
*
* Description:
* Gets data for a given property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id.
* LPVOID [in]: property parameters.
* ULONG [in]: size of property parameters.
* LPVOID [out]: receives property data.
* PULONG [in/out]: size of property data.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::UnsupportedGetHandler"
HRESULT CDirectSoundSecondaryBufferPropertySet::UnsupportedGetHandler(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, PULONG pcbPropertyData)
{
HRESULT hr;
DPF_ENTER();
hr = CDirectSoundPropertySet::GetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, pcbPropertyData);
DPF_LEAVE_HRESULT(hr);
return hr;
}
/***************************************************************************
*
* UnsupportedSetHandler
*
* Description:
* Sets data for a given property.
*
* Arguments:
* REFGUID [in]: property set id.
* ULONG [in]: property id.
* LPVOID [in]: property parameters.
* ULONG [in]: size of property parameters.
* LPVOID [in]: property data.
* ULONG [in]: size of property data.
*
* Returns:
* HRESULT: DirectSound/COM result code.
*
***************************************************************************/
#undef DPF_FNAME
#define DPF_FNAME "CDirectSoundSecondaryBufferPropertySet::UnsupportedSetHandler"
HRESULT CDirectSoundSecondaryBufferPropertySet::UnsupportedSetHandler(REFGUID guidPropertySetId, ULONG ulPropertyId, LPVOID pvPropertyParams, ULONG cbPropertyParams, LPVOID pvPropertyData, ULONG cbPropertyData)
{
HRESULT hr;
DPF_ENTER();
hr = CDirectSoundPropertySet::SetProperty(guidPropertySetId, ulPropertyId, pvPropertyParams, cbPropertyParams, pvPropertyData, cbPropertyData);
DPF_LEAVE_HRESULT(hr);
return hr;
}
| 219,191 | 73,283 |
//
// This file is a part of UERANSIM open source project.
// Copyright (c) 2021 ALİ GÜNGÖR.
//
// The software and all associated files are licensed under GPL-3.0
// and subject to the terms and conditions defined in LICENSE file.
//
#include <array>
#include <functional>
#include <optional>
#include <type_traits>
#include <vector>
#include <utils/common.hpp>
#include <utils/json.hpp>
namespace nas
{
// TODO: Periodun sonuna geldiğinde erişilmezse, (autoClearIfNecessary çağrılmazsa) delete yapılmaz backup çalışmaz
/*
* - Items are unique, if already exists, deletes the previous one
* - List have fixed size, if capacity is full, oldest item is deleted
* - Automatically cleared after specified period
* - The list is NOT thread safe
*/
template <typename T>
class NasList
{
public:
using backup_functor_type = std::function<void(const std::vector<T> &buffer, size_t count)>;
private:
const size_t m_sizeLimit;
const int64_t m_autoClearingPeriod;
const std::optional<backup_functor_type> m_backupFunctor;
std::vector<T> m_data;
size_t m_size;
int64_t m_lastAutoCleared;
public:
NasList(size_t sizeLimit, int64_t autoClearingPeriod, std::optional<backup_functor_type> backupFunctor)
: m_sizeLimit{sizeLimit}, m_autoClearingPeriod{autoClearingPeriod},
m_backupFunctor{backupFunctor}, m_data{sizeLimit}, m_size{}, m_lastAutoCleared{::utils::CurrentTimeMillis()}
{
}
NasList(const NasList &) = delete;
NasList(NasList &&) = delete;
public:
void add(const T &item)
{
autoClearIfNecessary();
remove(item);
makeSlotForNewItem();
m_data[m_size] = item;
m_size++;
touch();
}
void add(T &&item)
{
autoClearIfNecessary();
remove(item);
makeSlotForNewItem();
m_data[m_size] = std::move(item);
m_size++;
touch();
}
void remove(const T &item)
{
autoClearIfNecessary();
size_t index = ~0u;
for (size_t i = 0; i < m_size; i++)
{
if (m_data[i] == item)
{
index = i;
break;
}
}
if (index != ~0u)
removeAt(index);
}
bool contains(const T &item)
{
autoClearIfNecessary();
for (size_t i = 0; i < m_size; i++)
if (m_data[i] == item)
return true;
return false;
}
template <typename Functor>
void forEach(Functor &&fun)
{
autoClearIfNecessary();
for (size_t i = 0; i < m_size; i++)
fun((const T &)m_data[i]);
}
template <typename Functor>
void mutateForEach(Functor &&fun)
{
autoClearIfNecessary();
for (size_t i = 0; i < m_size; i++)
fun(m_data[i]);
touch();
}
void clear()
{
int64_t currentTime = ::utils::CurrentTimeMillis();
if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod)
m_lastAutoCleared = currentTime;
m_data.clear();
m_size = 0;
touch();
}
[[nodiscard]] size_t size() const
{
autoClearIfNecessary();
return m_data.size();
}
private:
void autoClearIfNecessary()
{
if (m_autoClearingPeriod <= 0)
return;
int64_t currentTime = ::utils::CurrentTimeMillis();
if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod)
{
m_lastAutoCleared = currentTime;
clear();
}
}
void makeSlotForNewItem()
{
if (m_size >= m_sizeLimit)
removeAt(0);
}
void removeAt(size_t index)
{
for (size_t i = index; i < m_size; ++i)
m_data[i] = i + 1 < m_sizeLimit ? m_data[i + 1] : T{};
m_size--;
touch();
}
void touch()
{
if (m_backupFunctor)
(*m_backupFunctor)(m_data, m_size);
}
};
template <typename T>
class NasSlot
{
public:
using backup_functor_type = std::function<void(const T &value)>;
private:
const int64_t m_autoClearingPeriod;
const std::optional<backup_functor_type> m_backupFunctor;
T m_value;
int64_t m_lastAutoCleared;
static_assert(!std::is_reference<T>::value);
public:
NasSlot(int64_t autoClearingPeriod, std::optional<backup_functor_type> backupFunctor)
: m_autoClearingPeriod{autoClearingPeriod}, m_backupFunctor{backupFunctor}, m_value{},
m_lastAutoCleared{::utils::CurrentTimeMillis()}
{
}
const T &get()
{
autoClearIfNecessary();
return m_value;
}
const T &getPure() const
{
return m_value;
}
void clear()
{
set(T{});
}
void set(const T &value)
{
autoClearIfNecessary();
m_value = value;
touch();
}
void set(T &&value)
{
autoClearIfNecessary();
m_value = std::move(value);
touch();
}
template <typename Functor>
void access(Functor fun)
{
autoClearIfNecessary();
fun((const T &)m_value);
}
template <typename Functor>
void mutate(Functor fun)
{
autoClearIfNecessary();
fun((T &)m_value);
touch();
}
private:
void autoClearIfNecessary()
{
if (m_autoClearingPeriod <= 0)
return;
int64_t currentTime = ::utils::CurrentTimeMillis();
if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod)
{
m_lastAutoCleared = currentTime;
m_value = {};
}
}
void touch()
{
if (m_backupFunctor)
(*m_backupFunctor)(m_value);
}
};
} // namespace nas
template <typename T>
inline Json ToJson(const nas::NasSlot<T> &v)
{
return ToJson(v.getPure());
}
| 5,882 | 2,054 |
/*
Copyright 2003 by Marc J. Rochkind. All rights reserved.
May be copied only for purposes and under conditions described
on the Web page www.basepath.com/aup/copyright.htm.
The Example Files are provided "as is," without any warranty;
without even the implied warranty of merchantability or fitness
for a particular purpose. The author and his publisher are not
responsible for any damages, direct or incidental, resulting
from the use or non-use of these Example Files.
The Example Files may contain defects, and some contain deliberate
coding mistakes that were included for educational reasons.
You are responsible for determining if and how the Example Files
are to be used.
*/
#ifndef _UXSYSVIPC_HPP_
#define _UXSYSVIPC_HPP_
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
namespace Ux {
/**
\ingroup Ux
*/
class SysVIPC : public Base {
protected:
int id;
public:
SysVIPC(int n = -1)
: id(n)
{ }
static key_t ftok(const char *path, int id);
operator int()
{ return id; }
};
/**
\ingroup Ux
*/
class SysVMsg : public SysVIPC {
public:
void get(key_t key, int flags = IPC_CREAT | PERM_FILE);
void ctl(int cmd, struct msqid_ds *data = NULL);
void snd(const void *msgp, size_t msgsize, int flags = 0);
ssize_t rcv(void *msgp, size_t mtextsize, long msgtype = 0, int flags = 0);
};
/**
\ingroup Ux
*/
class SysVShm : public SysVIPC {
public:
void get(key_t key, size_t size, int flags = IPC_CREAT | PERM_FILE);
void ctl(int cmd, struct shmid_ds *data = NULL);
void * at(const void *shmaddr = NULL, int flags = 0);
void dt(const void *shmaddr);
};
/**
\ingroup Ux
Union defined by SUS, but not in any standard header.
*/
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
/**
\ingroup Ux
*/
class SysVSem : public SysVIPC {
public:
void get(key_t key, int nsems, int flags = IPC_CREAT | PERM_FILE);
int ctl(int semnum, int cmd, union semun arg);
void op(struct sembuf *sops, size_t nsops);
};
} // namespace
#endif // _UXSYSVIPC_HPP_
| 2,048 | 796 |
/** @defgroup MleDPPType Magic Lantern Digital Playprint Library API - Type */
/**
* @file DppScalarArray.h
* @ingroup MleDPPType
*
* This file implements the scalar array data type used by the Magic Lantern Digital
* Playprint Library API.
*
* @author Mark S. Millard
* @created February 6, 2004
*/
// COPYRIGHT_BEGIN
//
// Copyright (c) 2015 Wizzer Works
//
// 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.
//
// For information concerning this source file, contact Mark S. Millard,
// of Wizzer Works at msm@wizzerworks.com.
//
// More information concerning Wizzer Works may be found at
//
// http://www.wizzerworks.com
//
// COPYRIGHT_END
// Include Magic Lantern header files.
#include "mle/mlMalloc.h"
// Include Digital Playprint header files.
#include "mle/DppScalar.h"
#include "mle/DppScalarArray.h"
//
// int array class
//
MLE_DWP_DATATYPE_SOURCE(MleDppScalarArray,"ScalarArray",MleDppArray);
//
// The MlScalar type might be a float or a long 16.16 fixed point
// number. Or it might be a class encapsulating one of those.
// Read/write the thing as a floating point number for the sake
// of numerics and having a fixed interchange format (esp if we
// go to 16.16 AND 20.12 fixed point numbers).
//
// Read into the data union as a float, then convert to fixed/float
// scalar type on the get()/set().
int
MleDppScalarArray::readElement(MleDwpInput *in,void *data) const
{
return in->readFloat((float *)data);
}
int
MleDppScalarArray::writeElement(MleDwpOutput *out,void *data) const
{
return out->writeFloat(*(float *)data);
}
int
MleDppScalarArray::writeElement(MleDppActorGroupOutput *out,void *data) const
{
return out->writeScalar(*(float *)data);
}
int
MleDppScalarArray::getElementSize(void) const
{
return sizeof(MlScalar);
}
void
MleDppScalarArray::setElement(MleDwpDataUnion *data,void *src) const
{
SET_FLOAT_FROM_SCALAR(*(float *)(data->m_u.v),src);
}
void
MleDppScalarArray::getElement(MleDwpDataUnion *data,void *dst) const
{
SET_SCALAR_FROM_FLOAT(dst,*(float *)(data->m_u.v));
}
void
MleDppScalarArray::set(MleDwpDataUnion *data,void *src) const
{
data->setDatatype(this);
data->m_u.v = new MleArray<MlScalar> ( *(MleArray<MlScalar> *)src );
}
void
MleDppScalarArray::get(MleDwpDataUnion *data,void *dst) const
{
*(MleArray<MlScalar> *)dst = *(MleArray<MlScalar> *)data->m_u.v;
}
void *
MleDppScalarArray::operator new(size_t tSize)
{
void *p = mlMalloc(tSize);
return p;
}
void
MleDppScalarArray::operator delete(void *p)
{
mlFree(p);
}
| 3,550 | 1,294 |
//
// Created by Peng,Wei(BAMRD) on 2021/4/2.
// https://github.com/tosone/bundleNode/blob/aaf04fd200a56f3f5b60c1c691877c192c6448af/deps/v8/src/startup-data-util.cc
//
#include <v8.h>
#include "V8Snapshot.h"
#include "V8Engine.h"
#include "GlobalObject.h"
#include "Utils.hpp"
#ifdef WIN32
#include <io.h>
#include <direct.h>
#else
#include <unistd.h>
#include <sys/stat.h>
#endif
#include <stdint.h>
#include <string>
#define MAX_PATH_LEN 256
#ifdef WIN32
#define ACCESS(fileName,accessMode) _access(fileName,accessMode)
#define MKDIR(path) _mkdir(path)
#else
#define ACCESS(fileName, accessMode) access(fileName,accessMode)
#define MKDIR(path) mkdir(path,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
#endif
#define MAX_PATH_LEN 256
using namespace v8;
v8::StartupData V8Snapshot::makeSnapshot() {
auto external_references = createExtRef();
V8Engine v8Engine(external_references);
v8::StartupData data{nullptr, 0};
v8::SnapshotCreator creator(v8Engine.isolate, external_references.data(), nullptr);
{
v8::HandleScope scope(v8Engine.isolate);
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(v8Engine.isolate);
global->SetAccessor(String::NewFromUtf8(v8Engine.isolate, "x").ToLocalChecked(), GlobalObject::XGetter,
GlobalObject::XSetter);
printf("GlobalObject::Version point=%p\n", &GlobalObject::Version);
Local<FunctionTemplate> fun = v8::FunctionTemplate::New(v8Engine.isolate, GlobalObject::Version);
global->Set(v8Engine.isolate, "version", fun);
v8::Local<v8::Context> context = v8::Context::New(v8Engine.isolate, nullptr, global);
v8::Context::Scope context_scope(context);
{
v8::Local<v8::String> source =
v8::String::NewFromUtf8(v8Engine.isolate,
"if(typeof x == 'undefined'){x = 0}x++;function add(a,b) {return a+b;}var kk='##@';(typeof version === 'function'? version(): 'None')+ add(0.1,x);").ToLocalChecked();
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
v8::String::Utf8Value value(v8Engine.isolate, result);
printf("result = %s\n", *value);
// 必须要调用 AddContext
creator.AddContext(context);
creator.SetDefaultContext(context);
}
}
data = creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kKeep);
// 立即从 snapshot 恢复 context
restoreSnapshot(data, false);
return data;
}
// 从左到右依次判断文件夹是否存在,不存在就创建
// example: /home/root/mkdir/1/2/3/4/
// 注意:最后一个如果是文件夹的话,需要加上 '\' 或者 '/'
int32_t createDirectory(const std::string &directoryPath) {
uint32_t dirPathLen = directoryPath.length();
if (dirPathLen > MAX_PATH_LEN) {
return -1;
}
char tmpDirPath[MAX_PATH_LEN] = {0};
for (uint32_t i = 0; i < dirPathLen; ++i) {
tmpDirPath[i] = directoryPath[i];
if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/') {
if (ACCESS(tmpDirPath, 0) != 0) {
int32_t ret = MKDIR(tmpDirPath);
if (ret != 0) {
return ret;
}
}
}
}
return 0;
}
void V8Snapshot::restoreSnapshot(v8::StartupData &data, const bool createPlatform) {
printf("## restoreSnapshot ##\n");
if (createPlatform) {
v8::V8::InitializeICU();
v8::V8::InitializeExternalStartupDataFromFile(__FILE__);
platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
printf("version=%s\n", v8::V8::GetVersion());
}
// Create a new Isolate and make it the current one.
createParams = v8::Isolate::CreateParams();
createParams.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
createParams.snapshot_blob = &data;
createParams.external_references = createExtRef().data();
v8::Isolate *isolate = v8::Isolate::New(createParams);
{
v8::HandleScope handle_scope(isolate);
v8::TryCatch tryCatch(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// v8::Local<v8::Context> context = v8::Context::FromSnapshot(isolate, 0).ToLocalChecked();
// Enter the context for compiling and running the hello world script.
v8::Context::Scope context_scope(context);
{
v8::Local<v8::String> source =
v8::String::NewFromUtf8Literal(isolate,
"(typeof version === 'function')? x + version():'not found version()'");
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
v8::MaybeLocal<v8::Value> localResult = script->Run(context);
if (tryCatch.HasCaught() || localResult.IsEmpty()) {
Local<String> msg = tryCatch.Message()->Get();
v8::String::Utf8Value msgVal(isolate, msg);
printf("HasCaught => %s\n", *msgVal);
} else {
v8::Local<v8::Value> result = localResult.ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("restore add() = %s\n", *utf8);
}
}
}
if (createPlatform) {
isolate->Dispose();
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
delete createParams.array_buffer_allocator;
}
}
void V8Snapshot::writeFile(v8::StartupData data) {
char currentPath[MAX_PATH_LEN];
getcwd(currentPath, MAX_PATH_LEN);
printf("current path =%s\n", currentPath);
std::string path = currentPath;
FILE *file = fopen((path + "/a.blob").c_str(), "w");
fseek(file, 0, SEEK_END);
rewind(file);
int writeSize = fwrite(data.data, data.raw_size, 1, file);
printf("write size=%d\n", writeSize);
fclose(file);
}
void V8Snapshot::readFile(v8::StartupData &data) {
char currentPath[MAX_PATH_LEN];
getcwd(currentPath, MAX_PATH_LEN);
printf("current path =%s\n", currentPath);
std::string path = currentPath;
FILE *file = fopen((path + "/a.blob").c_str(), "rb");
fseek(file, 0, SEEK_END);
data.raw_size = static_cast<int>(ftell(file));
rewind(file);
data.data = new char[data.raw_size];
int read_size = static_cast<int>(fread(const_cast<char *>(data.data),
1, data.raw_size, file));
fclose(file);
printf("readFile ## raw_size =%d, IsValid=%d, CanBeRehashed=%d, read_size=%d\n",
data.raw_size, data.IsValid(), data.CanBeRehashed(), read_size);
}
std::vector<intptr_t> V8Snapshot::createExtRef() {
std::vector<intptr_t> external_references;
external_references.reserve(3);
external_references.push_back((intptr_t) &GlobalObject::Version);
external_references.push_back((intptr_t) &GlobalObject::XGetter);
external_references.push_back((intptr_t) &GlobalObject::XSetter);
return external_references;
}
| 7,330 | 2,526 |
#include "StdAfx.h"
#include "LinesParser.h"
using namespace AsciiArt::Parser;
LinesParser::LinesParser(void)
{
}
LinesParser::~LinesParser(void)
{
}
| 154 | 61 |
#include "Sokoban.hpp"
Sokoban::Sokoban() :
m_window_size{ 640u, 640u },
m_distance{ 64.f },
m_tile_size{ m_distance, m_distance },
m_window{ sf::VideoMode{ m_window_size.x, m_window_size.y }, "05 - Map - SFML Workshop" }
{
m_window.setFramerateLimit(60);
m_texture_holder.load("tilesheet", "assets/tilesheet.png");
init_player();
init_map();
}
void Sokoban::run()
{
while (m_window.isOpen())
{
handle_events();
update();
render();
}
}
void Sokoban::handle_events()
{
for (auto event = sf::Event{}; m_window.pollEvent(event);)
{
if (event.type == sf::Event::Closed)
{
m_window.close();
}
handle_keyboard_input(event);
}
}
void Sokoban::update()
{
const auto next_position = m_player.getPosition() + (sf::Vector2f{ m_direction } * m_distance);
m_direction = sf::Vector2i{};
if (check_window_bounds(next_position) && !m_map.check_collision(next_position, { 0, 85, 90 }))
{
m_player.setPosition(next_position);
}
}
void Sokoban::render()
{
m_window.clear(sf::Color{ 0xAA733CFF });
m_window.draw(m_map);
m_window.draw(m_player);
m_window.display();
}
void Sokoban::init_player()
{
m_player.setTexture(m_texture_holder.get("tilesheet"));
m_player.setPosition(m_tile_size * 2.f);
m_player.setTextureRect({
0,
5 * static_cast<int>(m_tile_size.y),
static_cast<int>(m_tile_size.x),
static_cast<int>(m_tile_size.y)
});
}
void Sokoban::init_map()
{
std::vector<int> data =
{
90, 90, 90, 85, 85, 85, 85, 85, 90, 90,
90, 85, 85, 85, 89, 89, 89, 85, 90, 90,
90, 85, 102, 89, 89, 89, 89, 85, 90, 90,
90, 85, 85, 85, 89, 89, 102, 85, 90, 90,
90, 85, 102, 85, 85, 89, 89, 85, 90, 90,
90, 85, 89, 85, 89, 102, 89, 85, 85, 90,
90, 85, 89, 89, 102, 89, 89, 102, 85, 90,
90, 85, 89, 89, 89, 102, 89, 89, 85, 90,
90, 85, 85, 85, 85, 85, 85, 85, 85, 90,
90, 90, 90, 90, 90, 90, 90, 90, 90, 90,
};
m_map.load(m_texture_holder.get("tilesheet"), { 64u, 64u }, data.data(), { 10u, 10u });
}
void Sokoban::handle_keyboard_input(const sf::Event event)
{
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Left && !m_key_states[sf::Keyboard::Left])
{
m_direction.x = -1;
m_key_states[sf::Keyboard::Left] = true;
}
else if (event.key.code == sf::Keyboard::Right && !m_key_states[sf::Keyboard::Right])
{
m_direction.x = 1;
m_key_states[sf::Keyboard::Right] = true;
}
else if (event.key.code == sf::Keyboard::Up && !m_key_states[sf::Keyboard::Up])
{
m_direction.y = -1;
m_key_states[sf::Keyboard::Up] = true;
}
else if (event.key.code == sf::Keyboard::Down && !m_key_states[sf::Keyboard::Down])
{
m_direction.y = 1;
m_key_states[sf::Keyboard::Down] = true;
}
}
else if (event.type == sf::Event::KeyReleased)
{
if (event.key.code == sf::Keyboard::Left)
{
m_direction.x = 0;
m_key_states[sf::Keyboard::Left] = false;
}
else if (event.key.code == sf::Keyboard::Right)
{
m_direction.x = 0;
m_key_states[sf::Keyboard::Right] = false;
}
else if (event.key.code == sf::Keyboard::Up)
{
m_direction.y = 0;
m_key_states[sf::Keyboard::Up] = false;
}
else if (event.key.code == sf::Keyboard::Down)
{
m_direction.y = 0;
m_key_states[sf::Keyboard::Down] = false;
}
}
}
bool Sokoban::check_window_bounds(const sf::Vector2<float> next_position) const
{
return next_position.x >= 0.f && next_position.x <= m_window_size.x - m_distance
&& next_position.y >= 0.f && next_position.y <= m_window_size.y - m_distance;
}
| 4,037 | 1,756 |
/* Copyright (c) 2019 Hans-Kristian Arntzen
*
* 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
#include <string.h>
#include <atomic>
static_assert(sizeof(std::atomic<uint32_t>) == sizeof(uint32_t), "Atomic size mismatch. This type likely requires a lock to work.");
// A simple cross-process FIFO-like mechanism.
// We're not going to bother too much if messages are dropped, since they are mostly informative.
namespace Fossilize
{
enum { ControlBlockMessageSize = 64 };
enum { ControlBlockMagic = 0x19bcde1b };
enum { MaxProcessStats = 256 };
struct SharedControlBlock
{
uint32_t version_cookie;
// Used to implement a lock (or spinlock).
int futex_lock;
// Progress. Just need atomics to implement this.
std::atomic<uint32_t> successful_modules;
std::atomic<uint32_t> successful_graphics;
std::atomic<uint32_t> successful_compute;
std::atomic<uint32_t> skipped_graphics;
std::atomic<uint32_t> skipped_compute;
std::atomic<uint32_t> cached_graphics;
std::atomic<uint32_t> cached_compute;
std::atomic<uint32_t> clean_process_deaths;
std::atomic<uint32_t> dirty_process_deaths;
std::atomic<uint32_t> parsed_graphics;
std::atomic<uint32_t> parsed_compute;
std::atomic<uint32_t> parsed_graphics_failures;
std::atomic<uint32_t> parsed_compute_failures;
std::atomic<uint32_t> parsed_module_failures;
std::atomic<uint32_t> total_graphics;
std::atomic<uint32_t> total_compute;
std::atomic<uint32_t> total_modules;
std::atomic<uint32_t> banned_modules;
std::atomic<uint32_t> module_validation_failures;
std::atomic<uint32_t> progress_started;
std::atomic<uint32_t> progress_complete;
std::atomic<uint32_t> static_total_count_graphics;
std::atomic<uint32_t> static_total_count_compute;
std::atomic<uint32_t> num_running_processes;
std::atomic<uint32_t> num_processes_memory_stats;
std::atomic<uint32_t> metadata_shared_size_mib;
// Could be 64-bit, but we can express up to ~4 * 10^15 bytes this way.
// 64-bit would need some form of locking on 32-bit arch.
std::atomic<uint32_t> process_reserved_memory_mib[MaxProcessStats];
std::atomic<uint32_t> process_shared_memory_mib[MaxProcessStats];
std::atomic<int32_t> dirty_pages_mib;
std::atomic<int32_t> io_stall_percentage;
// Ring buffer. Needs lock.
uint32_t write_count;
uint32_t read_count;
uint32_t read_offset;
uint32_t write_offset;
uint32_t ring_buffer_offset;
uint32_t ring_buffer_size;
};
// These are not thread-safe. Need to lock them by external means.
static inline uint32_t shared_control_block_read_avail(SharedControlBlock *control_block)
{
uint32_t ret = control_block->write_count - control_block->read_count;
return ret;
}
static inline uint32_t shared_control_block_write_avail(SharedControlBlock *control_block)
{
uint32_t ret = 0;
uint32_t max_capacity_write_count = control_block->read_count + control_block->ring_buffer_size;
if (control_block->write_count >= max_capacity_write_count)
ret = 0;
else
ret = max_capacity_write_count - control_block->write_count;
return ret;
}
static inline bool shared_control_block_read(SharedControlBlock *control_block,
void *data_, uint32_t size)
{
auto *data = static_cast<uint8_t *>(data_);
const uint8_t *ring = reinterpret_cast<const uint8_t *>(control_block) + control_block->ring_buffer_offset;
if (size > control_block->ring_buffer_size)
return false;
if (size > (control_block->write_count - control_block->read_count))
return false;
uint32_t read_first = control_block->ring_buffer_size - control_block->read_offset;
uint32_t read_second = 0;
if (read_first > size)
read_first = size;
read_second = size - read_first;
memcpy(data, ring + control_block->read_offset, read_first);
if (read_second)
memcpy(data + read_first, ring, read_second);
control_block->read_offset = (control_block->read_offset + size) & (control_block->ring_buffer_size - 1);
control_block->read_count += size;
return true;
}
static inline bool shared_control_block_write(SharedControlBlock *control_block,
const void *data_, uint32_t size)
{
auto *data = static_cast<const uint8_t *>(data_);
uint8_t *ring = reinterpret_cast<uint8_t *>(control_block) + control_block->ring_buffer_offset;
if (size > control_block->ring_buffer_size)
return false;
uint32_t max_capacity_write_count = control_block->read_count + control_block->ring_buffer_size;
if (control_block->write_count + size > max_capacity_write_count)
return false;
uint32_t write_first = control_block->ring_buffer_size - control_block->write_offset;
uint32_t write_second = 0;
if (write_first > size)
write_first = size;
write_second = size - write_first;
memcpy(ring + control_block->write_offset, data, write_first);
if (write_second)
memcpy(ring, data + write_first, write_second);
control_block->write_offset = (control_block->write_offset + size) & (control_block->ring_buffer_size - 1);
control_block->write_count += size;
return true;
}
}
| 6,047 | 2,167 |
// Copyright 2012-2020 Jan Niklas Hasse <jhasse@bixense.com>
// For conditions of distribution and use, see copyright notice in LICENSE.txt
/// Functions for drawing shapes
/// @file
#pragma once
#include "Color.hpp"
#include "Vec2.hpp"
namespace jngl {
/// Sets the color which should be used to draw primitives
///
/// Doesn't change the alpha value currently set by setAlpha()
void setColor(jngl::Color rgb);
void setColor(jngl::Color, unsigned char alpha);
void setColor(unsigned char red, unsigned char green, unsigned char blue);
void setColor(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha);
/// Sets the alpha value which should be used to draw primitives (0 = fully transparent, 255 = fully
/// opaque)
void setAlpha(uint8_t alpha);
void pushAlpha(unsigned char alpha);
void popAlpha();
void setLineWidth(float width);
void drawLine(Vec2 start, Vec2 end);
void drawLine(double xstart, double ystart, double xend, double yend);
void drawEllipse(float xmid, float ymid, float width, float height, float startAngle = 0);
void drawEllipse(Vec2, float width, float height, float startAngle = 0);
void drawCircle(Vec2, float radius, float startAngle = 0);
void drawPoint(double x, double y);
void drawTriangle(Vec2 a, Vec2 b, Vec2 c);
void drawTriangle(double A_x, double A_y, double B_x, double B_y, double C_x, double C_y);
void drawRect(double xposition, double yposition, double width, double height);
/// Draws a rectangle at \a position
///
/// Use setColor(Color) to change the color and setAlpha(uint8_t) to change the translucency.
void drawRect(Vec2 position, Vec2 size);
template <class Vect> void drawRect(Vect pos, Vect size) {
drawRect(pos.x, pos.y, size.x, size.y);
}
} // namespace jngl
| 1,762 | 564 |
// We index inline namespaces.
//- @ns defines/binding NamespaceNS
inline namespace ns {
}
| 91 | 27 |
// Generated from /POI/java/org/apache/poi/ss/formula/function/FunctionMetadata.java
#include <org/apache/poi/ss/formula/function/FunctionMetadata.hpp>
#include <java/lang/Class.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuffer.hpp>
#include <Array.hpp>
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::ss::formula::function::FunctionMetadata::FunctionMetadata(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::ss::formula::function::FunctionMetadata::FunctionMetadata(int32_t index, ::java::lang::String* name, int32_t minParams, int32_t maxParams, int8_t returnClassCode, ::int8_tArray* parameterClassCodes)
: FunctionMetadata(*static_cast< ::default_init_tag* >(0))
{
ctor(index,name,minParams,maxParams,returnClassCode,parameterClassCodes);
}
constexpr int16_t poi::ss::formula::function::FunctionMetadata::FUNCTION_MAX_PARAMS;
void poi::ss::formula::function::FunctionMetadata::ctor(int32_t index, ::java::lang::String* name, int32_t minParams, int32_t maxParams, int8_t returnClassCode, ::int8_tArray* parameterClassCodes)
{
super::ctor();
_index = index;
_name = name;
_minParams = minParams;
_maxParams = maxParams;
_returnClassCode = returnClassCode;
_parameterClassCodes = (parameterClassCodes == nullptr) ? static_cast< ::int8_tArray* >(nullptr) : npc(parameterClassCodes)->clone();
}
int32_t poi::ss::formula::function::FunctionMetadata::getIndex()
{
return _index;
}
java::lang::String* poi::ss::formula::function::FunctionMetadata::getName()
{
return _name;
}
int32_t poi::ss::formula::function::FunctionMetadata::getMinParams()
{
return _minParams;
}
int32_t poi::ss::formula::function::FunctionMetadata::getMaxParams()
{
return _maxParams;
}
bool poi::ss::formula::function::FunctionMetadata::hasFixedArgsLength()
{
return _minParams == _maxParams;
}
int8_t poi::ss::formula::function::FunctionMetadata::getReturnClassCode()
{
return _returnClassCode;
}
int8_tArray* poi::ss::formula::function::FunctionMetadata::getParameterClassCodes()
{
return npc(_parameterClassCodes)->clone();
}
bool poi::ss::formula::function::FunctionMetadata::hasUnlimitedVarags()
{
return FUNCTION_MAX_PARAMS == _maxParams;
}
java::lang::String* poi::ss::formula::function::FunctionMetadata::toString()
{
auto sb = new ::java::lang::StringBuffer(int32_t(64));
npc(npc(sb)->append(npc(getClass())->getName()))->append(u" ["_j);
npc(npc(npc(sb)->append(_index))->append(u" "_j))->append(_name);
npc(sb)->append(u"]"_j);
return npc(sb)->toString();
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::ss::formula::function::FunctionMetadata::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.function.FunctionMetadata", 51);
return c;
}
java::lang::Class* poi::ss::formula::function::FunctionMetadata::getClass0()
{
return class_();
}
| 3,101 | 1,079 |
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Evangelos Anagnostopoulos, Soeren Sonnenburg, Bjoern Esser
*/
#include <gtest/gtest.h>
#include <shogun/features/streaming/StreamingHashedDocDotFeatures.h>
#include <shogun/lib/SGString.h>
#include <shogun/lib/SGStringList.h>
#include <shogun/lib/DelimiterTokenizer.h>
#include <shogun/converter/HashedDocConverter.h>
using namespace shogun;
TEST(StreamingHashedDocFeaturesTest, example_reading)
{
const char* doc_1 = "You're never too old to rock and roll, if you're too young to die";
const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam";
const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven";
SGString<char> string_1(65);
for (index_t i=0; i<65; i++)
string_1.string[i] = doc_1[i];
SGString<char> string_2(72);
for (index_t i=0; i<72; i++)
string_2.string[i] = doc_2[i];
SGString<char> string_3(85);
for (index_t i=0; i<85; i++)
string_3.string[i] = doc_3[i];
SGStringList<char> list(3,85);
list.strings[0] = string_1;
list.strings[1] = string_2;
list.strings[2] = string_3;
CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer();
tokenizer->delimiters[' '] = 1;
tokenizer->delimiters['\''] = 1;
tokenizer->delimiters[','] = 1;
CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, true);
CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE);
CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection,
tokenizer, 5);
index_t i = 0;
feats->start_parser();
while (feats->get_next_example())
{
SGSparseVector<float64_t> example = feats->get_vector();
SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false);
tmp.vector = list.strings[i].string;
SGSparseVector<float64_t> converted_doc = converter->apply(tmp);
EXPECT_EQ(example.num_feat_entries, converted_doc.num_feat_entries);
for (index_t j=0; j<example.num_feat_entries; j++)
{
EXPECT_EQ(example.features[j].feat_index, converted_doc.features[j].feat_index);
EXPECT_EQ(example.features[j].entry, converted_doc.features[j].entry);
}
feats->release_example();
i++;
}
feats->end_parser();
SG_UNREF(feats);
SG_UNREF(doc_collection);
SG_UNREF(converter);
}
TEST(StreamingHashedDocFeaturesTest, dot_tests)
{
const char* doc_1 = "You're never too old to rock and roll, if you're too young to die";
const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam";
const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven";
SGString<char> string_1(65);
for (index_t i=0; i<65; i++)
string_1.string[i] = doc_1[i];
SGString<char> string_2(72);
for (index_t i=0; i<72; i++)
string_2.string[i] = doc_2[i];
SGString<char> string_3(85);
for (index_t i=0; i<85; i++)
string_3.string[i] = doc_3[i];
SGStringList<char> list(3,85);
list.strings[0] = string_1;
list.strings[1] = string_2;
list.strings[2] = string_3;
CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer();
tokenizer->delimiters[' '] = 1;
tokenizer->delimiters['\''] = 1;
tokenizer->delimiters[','] = 1;
CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, true);
CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE);
CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection,
tokenizer, 5);
feats->start_parser();
SGVector<float32_t> dense_vec(32);
for (index_t j=0; j<32; j++)
dense_vec[j] = CMath::random(0.0, 1.0);
index_t i = 0;
while (feats->get_next_example())
{
/** Dense dot test */
SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false);
tmp.vector = list.strings[i].string;
SGSparseVector<float64_t> converted_doc = converter->apply(tmp);
float32_t tmp_res = 0;
for (index_t j=0; j<converted_doc.num_feat_entries; j++)
tmp_res += dense_vec[converted_doc.features[j].feat_index] * converted_doc.features[j].entry;
EXPECT_NEAR(tmp_res, feats->dense_dot(dense_vec.vector, dense_vec.vlen), 1e-7);
/** Add to dense test */
SGSparseVector<float64_t> example = feats->get_vector();
SGVector<float32_t> dense_vec2(32);
for (index_t j=0; j<32; j++)
dense_vec2[j] = dense_vec[j];
feats->add_to_dense_vec(1, dense_vec2.vector, dense_vec2.vlen);
index_t sparse_idx = 0;
for (index_t j=0; j<32; j++)
{
if ( (sparse_idx < example.num_feat_entries) &&
(example.features[sparse_idx].feat_index == j) )
{
EXPECT_NEAR(dense_vec2[j], dense_vec[j] + example.features[sparse_idx].entry, 1e-7);
sparse_idx++;
}
else
EXPECT_NEAR(dense_vec2[j], dense_vec[j], 1e-7);
}
feats->release_example();
i++;
}
feats->end_parser();
SG_UNREF(feats);
SG_UNREF(doc_collection);
SG_UNREF(converter);
}
| 4,952 | 2,111 |
#include "StdAfx.h"
#ifndef DISABLE_UNCOMMON
#include "BroadphaseInterface.h"
#include "CollisionConfiguration.h"
#include "DiscreteDynamicsWorldMultiThreaded.h"
#include "Dispatcher.h"
#include "SequentialImpulseConstraintSolver.h"
ConstraintSolverPoolMultiThreaded::ConstraintSolverPoolMultiThreaded(int numSolvers)
: ConstraintSolver(ALIGNED_NEW(btConstraintSolverPoolMt)(numSolvers))
{
}
DiscreteDynamicsWorldMultiThreaded::DiscreteDynamicsWorldMultiThreaded(BulletSharp::Dispatcher^ dispatcher,
BroadphaseInterface^ pairCache, ConstraintSolverPoolMultiThreaded^ constraintSolver,
BulletSharp::ConstraintSolver^ constraintSolverMultiThreaded, CollisionConfiguration^ collisionConfiguration)
{
if (!dispatcher)
{
throw gcnew ArgumentNullException("dispatcher");
}
if (!pairCache)
{
throw gcnew ArgumentNullException("pairCache");
}
if (!constraintSolver)
{
throw gcnew ArgumentNullException("constraintSolver");
}
auto native = new btDiscreteDynamicsWorldMt(dispatcher->_native,
pairCache->_native, (btConstraintSolverPoolMt*)constraintSolver->_native,
GetUnmanagedNullable(constraintSolverMultiThreaded),
GetUnmanagedNullable(collisionConfiguration));
_constraintSolver = constraintSolver;
SetInternalReferences(native, dispatcher, pairCache);
}
#endif
| 1,336 | 431 |
#include "shacl/optional.hpp"
#include "catch2/catch.hpp"
SCENARIO("value_or"){
struct U {
mutable bool copiedFrom = false;
mutable bool movedFrom = false;
};
struct T {
mutable bool copiedFrom = false;
mutable bool movedFrom = false;
T() = default;
T(T&& that) { that.movedFrom = true; }
T& operator=(T&&) { return *this; }
T(const T& that) { that.copiedFrom = true; }
T(U&& that) { that.movedFrom = true; }
T(const U& that) { that.copiedFrom = true; }
};
auto ignore = [](auto&&){};
shacl::Optional<T> o;
GIVEN("an optional const lvalue"){
const auto& co = o;
GIVEN("the optional is engaged"){
o = T{};
GIVEN("an argument of the optional parameter type"){
auto arg = T{};
THEN("the value_or method should copy the stored value"){
auto t = co.value_or(arg);
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
REQUIRE(co.value().copiedFrom);
REQUIRE_FALSE(co.value().movedFrom);
}
}
GIVEN("an argument convertible to the optional parameter type"){
auto arg = U{};
THEN("the value_or method should copy the stored value"){
auto t = co.value_or(arg);
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
REQUIRE(co.value().copiedFrom);
REQUIRE_FALSE(co.value().movedFrom);
}
}
}
GIVEN("the optional is disengaged"){
GIVEN("an argument of the optional parameter type"){
auto arg = T{};
GIVEN("the argument is an lvalue"){
THEN("the value_or method should copy the argument"){
auto t = co.value_or(arg);
ignore(t);
REQUIRE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
}
}
GIVEN("the argument is an rvalue"){
THEN("the value_or method should move the argument"){
auto t = co.value_or(std::move(arg));
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE(arg.movedFrom);
}
}
}
GIVEN("an argument convertible to the optional parameter type"){
auto arg = U{};
GIVEN("the argument is an lvalue"){
THEN("the value_or method should copy the argument"){
auto t = co.value_or(arg);
ignore(t);
REQUIRE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
}
}
GIVEN("the argument is an rvalue"){
THEN("the value_or method should move the argument"){
auto t = co.value_or(std::move(arg));
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE(arg.movedFrom);
}
}
}
}
}
GIVEN("an optional mutable rvalue"){
GIVEN("the optional is engaged"){
o = T{};
GIVEN("an argument of the optional parameter type"){
auto arg = T{};
THEN("the value_or method should move the stored value"){
auto t = std::move(o).value_or(arg);
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
REQUIRE_FALSE(o.value().copiedFrom);
REQUIRE(o.value().movedFrom);
}
}
GIVEN("an argument convertible to the optional parameter type"){
auto arg = U{};
THEN("the value_or method should move the stored value"){
auto t = std::move(o).value_or(arg);
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
REQUIRE_FALSE(o.value().copiedFrom);
REQUIRE(o.value().movedFrom);
}
}
}
GIVEN("the optional is disengaged"){
GIVEN("an argument of the optional parameter type"){
auto arg = T{};
GIVEN("the argument is an lvalue"){
THEN("the value_or method should copy the argument"){
auto t = std::move(o).value_or(arg);
ignore(t);
REQUIRE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
}
}
GIVEN("the argument is an rvalue"){
THEN("the value_or method should move the argument"){
auto t = std::move(o).value_or(std::move(arg));
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE(arg.movedFrom);
}
}
}
GIVEN("an argument convertible to the optional parameter type"){
auto arg = U{};
GIVEN("the argument is an lvalue"){
THEN("the value_or method should copy the argument"){
auto t = std::move(o).value_or(arg);
ignore(t);
REQUIRE(arg.copiedFrom);
REQUIRE_FALSE(arg.movedFrom);
}
}
GIVEN("the argument is an rvalue"){
THEN("the value_or method should move the argument"){
auto t = std::move(o).value_or(std::move(arg));
ignore(t);
REQUIRE_FALSE(arg.copiedFrom);
REQUIRE(arg.movedFrom);
}
}
}
}
}
}
| 5,170 | 1,668 |
#include "LdFile.h"
#include "Duden.h"
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
namespace duden {
LdFile parseLdFile(dictlsd::IRandomAccessStream* stream) {
LdFile ld;
ld.references.push_back({"WEB", "Web", "W"});
std::string line;
while (readLine(stream, line)) {
boost::algorithm::trim(line);
if (line.empty())
continue;
line = win1252toUtf8(line);
if (line[0] == 'G' || line[0] == 'g') {
boost::smatch m;
if (!boost::regex_match(line, m, boost::regex("^.(.*?)\\|(.*?)\\|(.*?)$")))
throw std::runtime_error("LD parsing error");
ld.references.push_back({m[1], m[2], m[3]});
} else if (line[0] == 'B') {
ld.name = line.substr(1);
} else if (line[0] == 'S') {
ld.sourceLanguage = line.substr(1);
} else if (line[0] == 'K') {
ld.baseFileName = line.substr(1);
} else if (line[0] == 'D') {
boost::smatch m;
if (!boost::regex_match(line, m, boost::regex("^D(.+?) (\\d+) (\\d+).*$")))
throw std::runtime_error("LD parsing error");
ld.ranges.push_back({m[1],
static_cast<uint32_t>(std::stoul(m[2])),
static_cast<uint32_t>(std::stoul(m[3]))});
}
}
return ld;
}
int dudenLangToCode(const std::string& lang) {
if (lang == "deu")
return 1031;
if (lang == "enu")
return 1033;
if (lang == "fra")
return 1036;
if (lang == "esn")
return 1034;
if (lang == "ita")
return 1040;
if (lang == "rus")
return 1049;
return 0;
}
void updateLanguageCodes(std::vector<LdFile*> lds) {
auto first = lds.at(0);
auto second = lds.size() > 1 ? lds.at(1) : nullptr;
auto firstSource = first->sourceLanguage;
auto secondSource = second ? second->sourceLanguage : "deu";
first->sourceLanguageCode = dudenLangToCode(firstSource);
first->targetLanguageCode = dudenLangToCode(secondSource);
if (second) {
second->sourceLanguageCode = dudenLangToCode(secondSource);
second->targetLanguageCode = dudenLangToCode(firstSource);
}
}
} // namespace duden
| 2,283 | 809 |
/*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "PtySky.h"
#include <QtToolbox/CollapsibleWidget.moc.h>
#include <QtToolbox/SingleSlidingValue.moc.h>
#include <QtToolbox/ColorPicker/QuickColorPicker.moc.h>
#include <QtToolbox/ComboBox.moc.h>
#include <Universe/World.h>
#include <QGridLayout>
#include <QCheckBox>
#include <EPI/GUI/Widget/CustomLine.moc.h>
namespace EPI
{
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PtySky::PtySky(const Ptr<Universe::World>& pWorld, const Core::String& title):
PropertyNode(title, true, false, CONTENT),
_skyTexture(pWorld->getSkyTexture()),
_color(pWorld->getSkyColor()),
_glow(pWorld->getSkyGlow()),
_horizon(pWorld->getSkyHorizon()),
_angle(pWorld->getSkyAngle()),
_roof(pWorld->getSkyRoof()),
_sphericity(pWorld->getSkySphericity()),
_atInfinity(pWorld->getSkyAtInfinity()),
_isProcedural(pWorld->isSkyProcedural()),
_model(pWorld->getSkyModel()),
_skyColor(pWorld->getSkyBackColor()),
_sunColor(pWorld->getSkySunColor()),
_intensity(pWorld->getSkySunIntensity()),
_pWorld(pWorld)
{
updateProperty();
}
//-----------------------------------------------------------------------------
PtySky::~PtySky()
{
}
//-----------------------------------------------------------------------------
Ptr<PropertyWidget> PtySky::internalCreatePropertyWidget(const Ptr<PropertyWidgetDataProxy>& pDataProxy, QWidget * parent)
{
Ptr<PtyWidgetSky> pPW (new PtyWidgetSky(pDataProxy, parent));
return pPW;
}
//-----------------------------------------------------------------------------
void PtySky::updateProperty()
{
_skyTexture = _pWorld->getSkyTexture();
_color = _pWorld->getSkyColor();
_glow = _pWorld->getSkyGlow();
_horizon = _pWorld->getSkyHorizon();
_angle = _pWorld->getSkyAngle();
_roof = _pWorld->getSkyRoof();
_sphericity = _pWorld->getSkySphericity();
_atInfinity = _pWorld->getSkyAtInfinity();
_isProcedural = _pWorld->isSkyProcedural();
_model = _pWorld->getSkyModel();
_skyColor = _pWorld->getSkyBackColor();
_sunColor = _pWorld->getSkySunColor();
_intensity = _pWorld->getSkySunIntensity();
}
//-----------------------------------------------------------------------------
void PtySky::updateData()
{
_pWorld->setSkyTexture(_skyTexture);
_pWorld->setSkyColor(_color);
_pWorld->setSkyGlow(_glow);
_pWorld->setSkyHorizon(_horizon);
_pWorld->setSkyAngle(_angle);
_pWorld->setSkyRoof(_roof);
_pWorld->setSkySphericity(_sphericity);
_pWorld->setSkyAtInfinity(_atInfinity);
_pWorld->setSkyProcedural(_isProcedural);
_pWorld->setSkyModel(_model);
_pWorld->setSkyBackColor(_skyColor);
_pWorld->setSkySunColor(_sunColor);
_pWorld->setSkySunIntensity(_intensity);
}
//-----------------------------------------------------------------------------
Ptr<Property> PtySky::clone() const
{
return Ptr<Property>(new PtySky( *this ));
}
//-----------------------------------------------------------------------------
void PtySky::internalCopy(const Ptr<Property>& pSrc)
{
Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(pSrc);
_skyTexture = pPtySky->_skyTexture;
_color = pPtySky->_color;
_glow = pPtySky->_glow;
_horizon = pPtySky->_horizon;
_angle = pPtySky->_angle;
_roof = pPtySky->_roof;
_sphericity = pPtySky->_sphericity;
_atInfinity = pPtySky->_atInfinity;
_isProcedural = pPtySky->_isProcedural;
_pWorld = pPtySky->_pWorld;
_model = pPtySky->_model;
_skyColor = pPtySky->_skyColor;
_sunColor = pPtySky->_sunColor;
_intensity = pPtySky->_intensity;
updateData();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PtyWidgetSky::PtyWidgetSky(const Ptr<PropertyWidgetDataProxy>& data, QWidget * parent):
PropertyWidget(data, parent)
{
setupUi();
}
//-----------------------------------------------------------------------------
PtyWidgetSky::~PtyWidgetSky()
{
}
//-----------------------------------------------------------------------------
void PtyWidgetSky::setupUi()
{
_layout = new QGridLayout(this);
_layout->setContentsMargins(0, 0, 0, 0);
_layout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
_groupBox = new QtToolbox::CollapsibleWidget(this, "Sky", false);
_groupBox->setStyle(QtToolbox::CW_TITLE_1);
_groupBox->setAlignmentTitle(Qt::AlignCenter);
QGridLayout* layoutGroupBox = new QGridLayout(NULL);
layoutGroupBox->setContentsMargins(0, 0, 0, 0);
_groupBox->setLayout(layoutGroupBox);
_skyTexture = new CustomLine(_groupBox, "Texture");
_skyTexture->pushAuthorizedDropMimeData("asset/texture");
_skyTexture->setReadOnly(true);
_color = new QtToolbox::QuickColorPicker(_groupBox, "Color", Qt::white, false);
_glow = new QtToolbox::QuickColorPicker(_groupBox, "Glow", Qt::white, false);
_horizon = new QtToolbox::SingleSlidingDouble(_groupBox, "Horizon", -1.0, 0.99);
_angle = new QtToolbox::SingleSlidingDouble(_groupBox, "Angle", 0, Core::rad2deg(d_PI_MUL_2));
_roof = new QtToolbox::SingleSlidingDouble(_groupBox, "Roof", 0.0, 5000.0);
_sphericity = new QtToolbox::SingleSlidingDouble(_groupBox, "Sphericity", 0.0, 1.0);
_atInfinity = new QCheckBox("At infinity", _groupBox);
_atInfinity->setChecked(true);
_isProcedural = new QCheckBox("Is procedural", _groupBox);
_isProcedural->setChecked(true);
_model = new QtToolbox::ComboBox(_groupBox, "Model");
_skyColor = new QtToolbox::QuickColorPicker(_groupBox, "Sky color", Qt::white, false);
_sunColor = new QtToolbox::QuickColorPicker(_groupBox, "Sun color", Qt::white, false);
_intensity = new QtToolbox::SingleSlidingDouble(_groupBox, "Intensity", 1.0, 4.0);
_model->addItem("Foggy");
_model->addItem("Cloudy");
_model->addItem("Clear sky");
layoutGroupBox->addWidget(_skyTexture, 0, 0, Qt::AlignCenter);
layoutGroupBox->addWidget(_color, 1, 0, Qt::AlignCenter);
layoutGroupBox->addWidget(_glow, 2, 0, Qt::AlignCenter);
layoutGroupBox->addWidget(_horizon, 3, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_angle, 4, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_roof, 5, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_sphericity, 6, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_atInfinity, 7, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_isProcedural,8, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_model, 9, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_skyColor, 10, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_sunColor, 11, 0, Qt::AlignLeft);
layoutGroupBox->addWidget(_intensity, 12, 0, Qt::AlignLeft);
_layout->addWidget(_groupBox);
getWidgetsForUndoRedo().push_back(_skyTexture);
getWidgetsForUndoRedo().push_back(_color);
getWidgetsForUndoRedo().push_back(_glow);
getWidgetsForUndoRedo().push_back(_horizon);
getWidgetsForUndoRedo().push_back(_angle);
getWidgetsForUndoRedo().push_back(_roof);
getWidgetsForUndoRedo().push_back(_sphericity);
getWidgetsForUndoRedo().push_back(_atInfinity);
getWidgetsForUndoRedo().push_back(_isProcedural);
getWidgetsForUndoRedo().push_back(_model);
getWidgetsForUndoRedo().push_back(_skyColor);
getWidgetsForUndoRedo().push_back(_sunColor);
getWidgetsForUndoRedo().push_back(_intensity);
PropertyWidget::setupUi();
}
//-----------------------------------------------------------------------------
void PtyWidgetSky::readProperty()
{
Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty());
_skyTexture->setText(Core::String8(pPtySky->_skyTexture).c_str());
_color->setColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a);
_glow->setColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a);
_horizon->setSingleValue(pPtySky->_horizon);
_angle->setSingleValue(Core::rad2deg(pPtySky->_angle));
_roof->setSingleValue(pPtySky->_roof);
_sphericity->setSingleValue(pPtySky->_sphericity);
_atInfinity->setChecked(pPtySky->_atInfinity);
_isProcedural->setChecked(pPtySky->_isProcedural);
_skyColor->setColorLinear(pPtySky->_skyColor);
_sunColor->setColorLinear(pPtySky->_sunColor);
_model->selectIndex(int(pPtySky->_model));
_intensity->setSingleValue(pPtySky->_intensity);
}
//-----------------------------------------------------------------------------
void PtyWidgetSky::writeProperty(QWidget* pWidget)
{
Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty());
pPtySky->_skyTexture = Core::String(_skyTexture->text().toStdString().c_str());
_color->getColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a);
_glow->getColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a);
_horizon->getSingleValue(pPtySky->_horizon);
double angle = 0.0;
_angle->getSingleValue(angle);
pPtySky->_angle = Core::deg2rad(angle);
_roof->getSingleValue(pPtySky->_roof);
_sphericity->getSingleValue(pPtySky->_sphericity);
pPtySky->_atInfinity = _atInfinity->isChecked();
pPtySky->_isProcedural = _isProcedural->isChecked();
_skyColor->getColorLinear(pPtySky->_skyColor);
_sunColor->getColorLinear(pPtySky->_sunColor);
pPtySky->_model = Renderer::ELightingModel(_model->selectedIndex());
_intensity->getSingleValue(pPtySky->_intensity);
}
//-----------------------------------------------------------------------------
} // namespace EPI | 12,202 | 4,230 |
#include "game.h"
Game::Game()
{
qrTexturePtr = new QResource(":/Textures/Resources/hex-tex.png");
qrFontPtr = new QResource(":/Fonts/Resources/Lato-Regular.ttf");
texture.loadFromMemory(qrTexturePtr->data(), qrTexturePtr->size()); //lading resources
font.loadFromMemory(qrFontPtr->data(), qrFontPtr->size());
delete qrTexturePtr;
delete qrFontPtr;
generateTemplate();
clickedAt = Tile();
}
Game::Game(bool) : Game()
{
banner = Banner(sf::Vector2f(0, 640 - 32), sf::Vector2f(640, 32), font);
}
void Game::clicked(sf::Vector2i pos, std::vector<Player> &players, Tile &clickedAt)
{
for (auto &player : players) {
for (auto &val : player.ownership()) {
if (val.getGlobalBounds().contains(pos.x, pos.y)) {
clickedAt = val;
break;
}
}
}
}
void Game::generateTemplate(sf::Vector2i tileSize, unsigned int mapSize)
{
std::vector<Tile> m_objects;
for (int i = 0; i < mapSize; ++i)
for (int j = 0; j < mapSize; ++j) {
if (j % 2 == 0) {
Tile temp(texture, tileSize, sf::Vector2f(i * tileSize.x * 2, 2 * j * tileSize.y));
temp.setUpTile(tileSize, sf::Vector2i(i, j), 0);
m_objects.emplace_back(temp);
} else {
Tile temp(texture,
tileSize,
sf::Vector2f(i * tileSize.x * 2 + tileSize.x, 2 * j * tileSize.y));
temp.setUpTile(tileSize, sf::Vector2i(i, j), 1);
m_objects.emplace_back(temp);
}
}
for (auto &obj : m_objects) {
obj.move(tileSize.x / 2, tileSize.y / 2);
}
MAP = m_objects;
}
std::vector<sf::VertexArray> Game::createLines(std::vector<Player> &players)
{
sf::VertexArray temp(sf::Lines, 2);
std::vector<sf::VertexArray> vec;
for (auto &playerM : players) {
for (auto &tileOne : playerM.ownership()) {
for (auto &player : players) {
for (auto &tileTwo : player.ownership()) {
if (tileOne.movePossible(tileTwo)) {
temp[0].color = sf::Color(100, 100, 100, 50);
temp[0].position = sf::Vector2f(tileOne.getGlobalBounds().left
+ (tileOne.getGlobalBounds().width / 2),
tileOne.getGlobalBounds().top
+ (tileOne.getGlobalBounds().height
/ 2));
temp[1].color = sf::Color(100, 100, 100, 50);
temp[1].position = sf::Vector2f(tileTwo.getGlobalBounds().left
+ (tileTwo.getGlobalBounds().width / 2),
tileTwo.getGlobalBounds().top
+ (tileTwo.getGlobalBounds().height
/ 2));
vec.emplace_back(temp);
}
}
}
}
}
return vec;
}
void Game::nextTurn(unsigned long long &turn, std::vector<Player> &players)
{
turn++;
if (turn >= players.size()) {
turn = 1;
}
while (players[turn].ownership().size() == 0) {
turn++;
if (turn >= players.size()) {
turn = 1;
}
}
}
void Game::gameLoop()
{
Lines = createLines(players);
TilesOnScreen = MAP.size();
sf::RenderWindow window(sf::VideoMode(640, 640), "Tile Conqueror");
window.setFramerateLimit(60);
window.setVerticalSyncEnabled(1);
while (window.isOpen()) { //config complete, window created, game starts
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if (event.type == event.MouseButtonReleased
&& event.mouseButton.button == sf::Mouse::Left) {
clicked(sf::Mouse::getPosition(window), players, clickedAt);
}
if (event.type == event.KeyReleased && event.key.code == sf::Keyboard::Space
&& !players[turn].AI()) {
if (pointsGiveAway) {
nextTurn(turn, players);
pointsGiveAway = 0;
//TODO if points left add 1 point from the remaining to every tile IF possible
continue;
}
players[turn].clearOrigin();
pointsGiveAway = 1;
pointsLeft = players[turn].ownership().size();
} //TODO add full value on PPM
}
window.clear(sf::Color::Black);
for (auto &line : Lines) {
window.draw(line);
}
for (auto &player : players) {
player.textCorrection();
player.colorCorrection();
}
if (!pointsGiveAway) {
Turnmanager(players, clickedAt, turn);
} else {
players[turn].addPointsToTiles(clickedAt, pointsLeft);
}
players[turn].hilightOrigin();
clickedAt = Tile();
////
for (auto player : players) {
for (auto val : player.ownership()) {
val.drawMe(window, font);
}
}
banner.refreshBanner(pointsLeft, players[turn], pointsGiveAway);
banner.drawMe(window);
window.display(); //koniec
for (auto &player : players) {
if (player.ownership().empty() && player.nickname() != "MAP") {
playersEmpty++;
}
}
if (TilesOnScreen == players[turn].ownership().size()
|| playersEmpty == players.size() - 2) //win condition
winCondition++;
if (winCondition >= 2)
break;
playersEmpty = 0;
} ///Game ended
window.close();
for (auto &player : players) {
if (!player.ownership().empty() && player.nickname() != "MAP" && winCondition >= 2) {
QMessageBox msg;
msg.setText(QString::fromStdString(player.nickname()) + " has won the game");
msg.exec();
}
}
return;
}
void Game::loadMap(QString path, std::vector<Player> &NewPlayers)
{
players = NewPlayers;
QFile file(path);
file.open(QFile::ReadOnly);
if (file.isOpen()) {
std::vector<sf::Vector2i> deleted;
QDataStream in(&file);
QString str;
int x, y;
while (!in.atEnd()) {
in >> x >> y;
deleted.emplace_back(sf::Vector2i(x, y));
}
file.close();
for (auto const &pos : deleted) {
for (auto tile = MAP.begin(); tile != MAP.end(); tile++) {
if (*tile == pos) {
tile->setColor(sf::Color(255, 0, 0, 100));
MAP.erase(tile);
tile--;
continue;
}
}
}
}
captureRandomTiles(MAP, players);
}
Game::~Game() {}
| 7,263 | 2,185 |
#include <iostream>
using namespace std;
int v[100001], st[512345];
inline int goleft(int n) {return n << 1;}
inline int goright(int n) {return (n << 1) + 1;}
void build(int n, int s, int e) {
if (s == e) {
st[n] = v[s];
} else {
int m = (s + e) >> 1;
build(goleft(n), s, m);
build(goright(n), m + 1, e);
st[n] = min(st[goleft(n)], st[goright(n)]);
}
}
int query(int n, int s, int e, int i, int j) {
if (s > j || e < i)
return 0x3f3f3f3f;
if (i <= s && e <= j)
return st[n];
int m = (s + e) >> 1;
int l = query(goleft(n), s, m, i, j);
int d = query(goright(n), m + 1, e, i, j);
return min(l, d);
}
int main()
{
int t, n, q, a, b, x = 1;
cin >> t;
while(t--) {
cin >> n >> q;
for (int i = 0; i < n; i++) {
cin >> v[i];
}
build(1, 0, n - 1);
cout << "Scenario #" << x++ << ":\n";
while(q--) {
cin >> a >> b;
cout << query(1, 0, n - 1, a - 1, b - 1) << endl;
}
}
return 0;
}
| 1,086 | 490 |
#include <iostream>
using std::cin;
using std::cout;
using std::iterator;
using std::begin;
using std::end;
/**
* Using pointers, write a program to set the elements in an array to zero.
*/
int main()
{
//Initialize a 10-length array.
int arr[10];
//Use pointer to assign each value to zero.
for (auto ptr = begin(arr); ptr != end(arr); ptr++)
*ptr = 0;
//Output each element's value.
for (auto ptr = begin(arr); ptr != end(arr); ptr++)
cout << *ptr << ' ';
return 0;
}
| 533 | 188 |
// ----------------------------------------------------------------------- //
//
// MODULE : LightningFX.cpp
//
// PURPOSE : Lightning special FX - Implementation
//
// CREATED : 4/15/99
//
// (c) 1999 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "LightningFX.h"
#include "iltclient.h"
#include "SFXMgr.h"
#include "iltcustomdraw.h"
#include "GameClientShell.h"
#include "DynamicLightFX.h"
#include "GameButes.h"
#include "VarTrack.h"
// ----------------------------------------------------------------------- //
//
// ROUTINE: CLightningFX::Init
//
// PURPOSE: Init the lightning fx
//
// ----------------------------------------------------------------------- //
LTBOOL CLightningFX::Init(HLOCALOBJ hServObj, HMESSAGEREAD hMessage)
{
if (!CSpecialFX::Init(hServObj, hMessage)) return LTFALSE;
if (!hMessage) return LTFALSE;
// Read in the init info from the message...
LFXCREATESTRUCT lcs;
lcs.hServerObj = hServObj;
lcs.lfx.hServerObj = hServObj;
g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vStartPos));
g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vEndPos));
g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.vLightColor));
g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vInnerColorStart));
g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vInnerColorEnd));
g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vOuterColorStart));
g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vOuterColorEnd));
lcs.lfx.fAlphaStart = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.lfx.fAlphaEnd = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.lfx.fMinWidth = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.lfx.fMaxWidth = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.lfx.fLifeTime = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.lfx.fAlphaLifeTime = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.fMinDelayTime = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.fMaxDelayTime = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.lfx.fPerturb = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.fLightRadius = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.fSoundRadius = g_pLTClient->ReadFromMessageFloat(hMessage);
lcs.lfx.nWidthStyle = g_pLTClient->ReadFromMessageByte(hMessage);
lcs.lfx.nNumSegments = g_pLTClient->ReadFromMessageByte(hMessage);
lcs.bOneTimeOnly = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage);
lcs.bDynamicLight = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage);
lcs.bPlaySound = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage);
lcs.lfx.bAdditive = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage);
lcs.lfx.bMultiply = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage);
m_hstrTexture = g_pLTClient->ReadFromMessageHString(hMessage);
return Init(&lcs);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CLightningFX::Init
//
// PURPOSE: Init the lightning fx
//
// ----------------------------------------------------------------------- //
LTBOOL CLightningFX::Init(SFXCREATESTRUCT* psfxCreateStruct)
{
if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE;
LFXCREATESTRUCT* pLFX = (LFXCREATESTRUCT*)psfxCreateStruct;
m_cs = *pLFX;
if (m_hstrTexture)
{
m_cs.lfx.pTexture = g_pLTClient->GetStringData(m_hstrTexture);
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CLightningFX::CreateObject
//
// PURPOSE: Create object associated the object
//
// ----------------------------------------------------------------------- //
LTBOOL CLightningFX::CreateObject(ILTClient *pClientDE)
{
if (!CSpecialFX::CreateObject(pClientDE)) return LTFALSE;
// Validate our init info...
if (m_cs.lfx.nNumSegments < 1) return LTFALSE;
// Get the thunder sound path if we need to play the sound...
if (m_cs.bPlaySound)
{
m_csThunderStr = g_pClientButeMgr->GetWeatherAttributeString(WEATHER_BUTE_THUNDERSOUND);
}
// Set up the lightning...
return Setup();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CLightningFX::Setup
//
// PURPOSE: Setup the line used to draw lightning
//
// ----------------------------------------------------------------------- //
LTBOOL CLightningFX::Setup()
{
// Figure out the position based on the object's current pos...
if (m_hServerObject)
{
LTVector vPos;
g_pLTClient->GetObjectPos(m_hServerObject, &vPos);
m_cs.lfx.vStartPos = vPos;
}
// Create our poly-line for the lightning...
if (m_Line.HasBeenDrawn())
{
m_Line.ReInit(&m_cs.lfx);
}
else
{
m_Line.Init(&m_cs.lfx);
m_Line.CreateObject(g_pLTClient);
}
// Figure out when to start/stop...
LTFLOAT fTime = g_pLTClient->GetTime();
m_fStartTime = fTime + GetRandom(m_cs.fMinDelayTime, m_cs.fMaxDelayTime);
m_fEndTime = m_fStartTime + m_cs.lfx.fLifeTime;
// Calculate our mid point...
LTVector vPos = m_cs.lfx.vStartPos;
LTVector vDir = (m_cs.lfx.vEndPos - m_cs.lfx.vStartPos);
float fDist = vDir.Mag();
float fTotalDist = fDist;
vDir.Norm();
m_vMidPos = (m_cs.lfx.vStartPos + (vDir * fDist/2.0f));
// Create the dynamic light if necessary...
if (m_cs.bDynamicLight && !m_hLight)
{
ObjectCreateStruct createStruct;
INIT_OBJECTCREATESTRUCT(createStruct);
createStruct.m_ObjectType = OT_LIGHT;
createStruct.m_Flags = FLAG_DONTLIGHTBACKFACING;
createStruct.m_Pos = m_vMidPos;
m_hLight = m_pClientDE->CreateObject(&createStruct);
if (!m_hLight) return LTFALSE;
m_pClientDE->SetLightColor(m_hLight, m_cs.vLightColor.x/255.0f,
m_cs.vLightColor.y/255.0f, m_cs.vLightColor.z/255.0f);
m_pClientDE->SetLightRadius(m_hLight, m_cs.fLightRadius);
}
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CLightningFX::HandleFirstTime
//
// PURPOSE: Handle the first time drawing...
//
// ----------------------------------------------------------------------- //
void CLightningFX::HandleFirstTime()
{
if (m_hLight)
{
uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight);
g_pLTClient->SetObjectFlags(m_hLight, dwFlags | FLAG_VISIBLE);
}
if (m_cs.bPlaySound)
{
float fWaitTime = 0.0f;
m_fPlaySoundTime = g_pLTClient->GetTime() + fWaitTime;
m_bPlayedSound = LTFALSE;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CLightningFX::UpdateSound
//
// PURPOSE: Handle playing the sound
//
// ----------------------------------------------------------------------- //
void CLightningFX::UpdateSound()
{
if (m_bPlayedSound || !m_cs.bPlaySound || (m_csThunderStr.GetLength() < 1)) return;
if (m_fPlaySoundTime <= g_pLTClient->GetTime())
{
m_bPlayedSound = LTTRUE;
g_pClientSoundMgr->PlaySoundFromPos(m_vMidPos, (char *)(LPCSTR)m_csThunderStr,
m_cs.fSoundRadius, SOUNDPRIORITY_MISC_MEDIUM);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CLightningFX::Update
//
// PURPOSE: Update the lightning
//
// ----------------------------------------------------------------------- //
LTBOOL CLightningFX::Update()
{
if (m_bWantRemove) return LTFALSE;
LTFLOAT fTime = g_pLTClient->GetTime();
// Hide/show lightning if necessary...
if (m_hServerObject)
{
uint32 dwUserFlags;
g_pLTClient->GetObjectUserFlags(m_hServerObject, &dwUserFlags);
if (!(dwUserFlags & USRFLG_VISIBLE))
{
m_Line.SetFlags(m_Line.GetFlags() & ~FLAG_VISIBLE);
if (m_hLight)
{
uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight);
g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE);
}
return LTTRUE;
}
else
{
m_Line.SetFlags(m_Line.GetFlags() | FLAG_VISIBLE);
}
}
m_Line.Update();
// See if it is time to act...
if (fTime > m_fEndTime)
{
if (m_cs.bOneTimeOnly)
{
return LTFALSE;
}
else
{
Setup();
m_bFirstTime = LTTRUE;
}
}
if (fTime < m_fStartTime)
{
m_Line.SetFlags(m_Line.GetFlags() & ~FLAG_VISIBLE);
if (m_hLight)
{
uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight);
g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE);
}
return LTTRUE; // not yet...
}
else
{
m_Line.SetFlags(m_Line.GetFlags() | FLAG_VISIBLE);
}
// Do first time stuff...
if (m_bFirstTime)
{
m_bFirstTime = LTFALSE;
HandleFirstTime();
}
else
{
if (m_hLight)
{
uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight);
g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE);
}
}
// Update playing the sound...
UpdateSound();
return LTTRUE;
}
| 9,042 | 3,419 |
//
// ShapeSphere.cpp
//
#include "ShapeSphere.h"
/*
========================================================================================================
ShapeSphere
========================================================================================================
*/
/*
====================================================
ShapeSphere::Support
====================================================
*/
Vec3 ShapeSphere::Support(const Vec3& dir, const Vec3& pos, const Quat& orient, const float bias) const
{
Vec3 supportPt;
// TODO: Add code
return supportPt;
}
/*
====================================================
ShapeSphere::InertiaTensor
====================================================
*/
Mat3 ShapeSphere::InertiaTensor() const
{
Mat3 tensor;
tensor.Zero();
tensor.rows[0][0] = 2.0f * m_radius * m_radius / 5.0f;
tensor.rows[1][1] = 2.0f * m_radius * m_radius / 5.0f;
tensor.rows[2][2] = 2.0f * m_radius * m_radius / 5.0f;
return tensor;
}
/*
====================================================
ShapeSphere::GetBounds
====================================================
*/
Bounds ShapeSphere::GetBounds(const Vec3& pos, const Quat& orient) const
{
Bounds tmp;
tmp.mins = Vec3(-m_radius) + pos;
tmp.maxs = Vec3(+m_radius) + pos;
return tmp;
}
/*
====================================================
ShapeSphere::GetBounds
====================================================
*/
Bounds ShapeSphere::GetBounds() const
{
Bounds tmp;
tmp.mins = Vec3(-m_radius);
tmp.maxs = Vec3(+m_radius);
return tmp;
} | 1,551 | 458 |
/*
* Copyright 2019 Xilinx, 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.
*/
/**
* @file aes.hpp
* @brief header file for Advanced Encryption Standard relate function.
* This file part of Vitis Security Library.
*
* @detail Currently we have Aes256_Encryption for AES256 standard.
*/
#ifndef _XF_SECURITY_MSG_PACK_HPP_
#define _XF_SECURITY_MSG_PACK_HPP_
#include <ap_int.h>
#include <stdint.h>
#include <hls_stream.h>
#ifndef __SYNTHESIS__
#include <iostream>
#endif
namespace xf {
namespace security {
namespace internal {
/**
* @brief Base class of msg packer
*
* @tparam W Bit width of one row. Support 64, 128, 256, 512.
*/
template <int W>
class packBase {
public:
int64_t msg_num;
int64_t curr_ptr; // not in bytes, in rows
int64_t buffer_size; // in bytes
int64_t total_row;
unsigned char* buffer_ptr;
bool isReset;
bool isMemAlloced;
packBase() {
#pragma HLS inline
#ifndef __SYNTHESIS__
isReset = false;
isMemAlloced = false;
#endif
}
/**
* @brief Reset records for packBase, need to be called each time a new pack to be process. reset function won't
* release any alloced memory. Should only be used on host side.
*/
void reset() {
msg_num = 0;
if (W == 64) {
curr_ptr = 2;
} else if (W == 128) {
curr_ptr = 1;
} else if (W == 256) {
curr_ptr = 1;
} else if (W == 512) {
curr_ptr = 1;
} else {
#ifndef __SYNTHESIS__
std::cout << W << " bits width of row is not supported. Only 64 / 128 / 256 / 512 is allowed." << std::endl;
#endif
}
buffer_size = 0;
buffer_ptr = nullptr;
isReset = true;
isMemAlloced = false;
}
/**
* @brief Assign alloced memory to packBase to process. Should only be used on host side.
*
* @param ptr Pointer to allocated memory.
* @size Size of allocated memory.
*/
void setPtr(unsigned char* ptr, int64_t size) {
buffer_ptr = ptr;
buffer_size = size;
total_row = buffer_size / (W / 8);
isMemAlloced = true;
}
/**
* @brief Finish a pack by adding number of message and effective rows of pack. This funciton need to be called once
* before send the package for processing. Should only be used on host side.
*
* @param ptr Pointer to allocated memory.
* @size Size of allocated memory.
*/
void finishPack() {
int64_t* header = (int64_t*)buffer_ptr;
header[0] = msg_num;
header[1] = curr_ptr;
}
};
/**
* @brief Base class of msg packer. Bit width of one row is 128.
*
* @tparam KeyW Bit width of key, only support 128, 192, 256
*/
template <int KeyW>
class aesCbcPack : public packBase<128> {
private:
void scanRaw(ap_uint<128>* ddr, ap_uint<64> row_num, hls::stream<ap_uint<128> >& rawStrm) {
for (ap_uint<64> i = 1; i < row_num; i++) {
#pragma HLS pipeline II = 1
ap_uint<128> tmp = ddr[i];
rawStrm.write(tmp);
}
}
void parsePack(ap_uint<64> msg_num,
hls::stream<ap_uint<128> >& rawStrm,
hls::stream<ap_uint<128> >& textStrm,
hls::stream<bool>& endTextStrm,
hls::stream<ap_uint<KeyW> >& keyStrm,
hls::stream<ap_uint<128> >& IVStrm,
hls::stream<ap_uint<64> >& lenStrm) {
for (ap_uint<64> i = 0; i < msg_num; i++) {
ap_uint<64> len = rawStrm.read();
ap_uint<128> iv = rawStrm.read();
ap_uint<128> keyL = rawStrm.read();
ap_uint<128> keyH = 0;
ap_uint<KeyW> key = 0;
if (KeyW > 128) {
keyH = rawStrm.read();
}
key.range(127, 0) = keyL;
key.range(KeyW - 1, 128) = keyH.range(KeyW - 129, 0);
keyStrm.write(key);
IVStrm.write(iv);
lenStrm.write(len);
for (ap_uint<64> i = 0; i < len; i += 16) {
#pragma HLS pipeline II = 1
textStrm.write(rawStrm.read());
endTextStrm.write(false);
}
endTextStrm.write(true);
}
}
void writeRaw(ap_uint<128>* ddr, hls::stream<ap_uint<128> >& rawStrm, hls::stream<ap_uint<16> >& numRawStrm) {
ap_uint<64> addr = 0;
ap_uint<16> numRaw = numRawStrm.read();
while (numRaw != 0) {
for (ap_uint<16> i = 0; i < numRaw; i++) {
#pragma HLS pipeline II = 1
ddr[addr + i] = rawStrm.read();
}
addr += numRaw;
numRaw = numRawStrm.read();
}
}
void preparePack(ap_uint<64> msg_num,
hls::stream<ap_uint<128> >& textStrm,
hls::stream<bool>& endTextStrm,
hls::stream<ap_uint<64> >& lenStrm,
hls::stream<ap_uint<128> >& rawStrm,
hls::stream<ap_uint<16> >& numRawStrm) {
ap_uint<16> numRaw = 0;
rawStrm.write(ap_uint<128>(msg_num));
numRaw++;
for (ap_uint<64> i = 0; i < msg_num; i++) {
rawStrm.write(ap_uint<128>(lenStrm.read()));
numRaw++;
if (numRaw == 64) {
numRaw = 0;
numRawStrm.write(ap_uint<16>(64));
}
while (!endTextStrm.read()) {
rawStrm.write(textStrm.read());
numRaw++;
if (numRaw == 64) {
numRaw = 0;
numRawStrm.write(ap_uint<16>(64));
}
}
}
if (numRaw != 0) {
numRawStrm.write(numRaw);
}
numRawStrm.write(0);
}
public:
aesCbcPack() {
#pragma HLS inline
}
#ifndef __SYNTHESIS__
/**
* @brief Add one message.
*
* @msg Pointer of message to be added.
* @len Length of message to be added.
* @iv Initialization vector of this message.
* @key Encryption key
* @return return true if successfully add message, other wise false.
*/
bool addOneMsg(unsigned char* msg, int64_t len, unsigned char* iv, unsigned char* key) {
if (!isReset) {
std::cout << "Not reset yet, please call reset()" << std::endl;
return false;
}
if (!isMemAlloced) {
std::cout << "Memory not alloced yet, please call setPtr()" << std::endl;
return false;
}
int64_t row_inc = 1 + 1 + (len + 15) / 16; // 1 for len, 1 for iv, 1 or 2 for key, (len + 15) / 16 for msg;
if (KeyW > 128) {
row_inc += 2;
} else {
row_inc += 1;
}
if (curr_ptr + row_inc > total_row) {
std::cout << "Memory left not enough to add one message" << std::endl;
return false;
}
memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 16);
*(int64_t*)(buffer_ptr + (curr_ptr * 16)) = len;
curr_ptr++;
memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 16);
memcpy((void*)(buffer_ptr + (curr_ptr * 16)), (void*)iv, 16);
curr_ptr++;
if (KeyW > 128) {
memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 32);
} else {
memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, 16);
}
memcpy((void*)(buffer_ptr + (curr_ptr * 16)), (void*)key, KeyW / 8);
if (KeyW > 128) {
curr_ptr += 2;
} else {
curr_ptr += 1;
}
memset((void*)(buffer_ptr + (curr_ptr * 16)), 0, (len + 15) / 16 * 16);
memcpy((void*)(buffer_ptr + (curr_ptr * 16)), (void*)msg, len);
curr_ptr += (len + 15) / 16;
msg_num++;
return true;
}
#endif
void scanPack(ap_uint<128>* ddr,
ap_uint<64> msg_num,
ap_uint<64> row_num,
hls::stream<ap_uint<128> >& textStrm,
hls::stream<bool>& endTextStrm,
hls::stream<ap_uint<KeyW> >& keyStrm,
hls::stream<ap_uint<128> >& IVStrm,
hls::stream<ap_uint<64> >& lenStrm) {
#pragma HLS dataflow
hls::stream<ap_uint<128> > rawStrm;
#pragma HLS stream variable = rawStrm depth = 128
scanRaw(ddr, row_num, rawStrm);
parsePack(msg_num, rawStrm, textStrm, endTextStrm, keyStrm, IVStrm, lenStrm);
}
void writeOutMsgPack(ap_uint<128>* ddr,
ap_uint<64> msg_num,
hls::stream<ap_uint<128> >& textStrm,
hls::stream<bool>& endTextStrm,
hls::stream<ap_uint<64> >& lenStrm) {
#pragma HLS dataflow
hls::stream<ap_uint<128> > rawStrm;
#pragma HLS stream variable = rawStrm depth = 128
hls::stream<ap_uint<16> > numRawStrm;
#pragma HLS stream variable = numRawStrm depth = 4
preparePack(msg_num, textStrm, endTextStrm, lenStrm, rawStrm, numRawStrm);
writeRaw(ddr, rawStrm, numRawStrm);
}
};
} // namespace internal
} // namespace security
} // namespace xf
#endif
| 9,670 | 3,510 |
#include "laws_cst.hpp"
#include "laws.hpp"
double rhov(const double &P_, const double &T_)
{
return P_/(R*T_);
}
double rhovdP(const double &P_, const double &T_)
{
return 1/(R*T_);
}
double rhovdT(const double &P_, const double &T_)
{
return -P_/(R*pow(T_,2.0));
}
/* Volumic mass of water -- */
double rhol(const double &P_, const double &T_)
{
return (-0.0025*(T_-273.156) - 0.1992)*(T_-273.156) + 1004.4;
}
double rholdP(const double &P_, const double &T_)
{
return 0;
}
double rholdT(const double &P_, const double &T_)
{
return (-2*0.0025*(T_-273.156) - 0.1992);
}
/* Specific enthalpy of vapor (J/kg) in fonction of Pressure (Pa) and Temperature (K) */
double h_v(const double &P_, const double &T_)
{
double c00 = 1.778741e+06;
double c10 = -6.997339e-02;
double c01 = 2.423675e+03;
double c20 = 1.958603e-10;
double c11 = 8.100784e-05;
double c02 = -3.747139e-01;
double c30 = -1.016123e-19;
double c21 = -1.234548e-13;
double c12 = -2.324528e-08;
double c03 = 1.891004e-04;
return c00 + c10*P_ + c01*T_
+ c20*pow(P_,2.0) + c11*P_*T_
+ c02*pow(T_,2.0) + c30*pow(P_,3.0)
+ c21*pow(P_,2.0)*T_ + c12*P_*pow(T_,2.0)
+ c03*pow(T_,3.0);
}
double h_vdP(const double &P_, const double &T_)
{
double c00 = 1.778741e+06;
double c10 = -6.997339e-02;
double c01 = 2.423675e+03;
double c20 = 1.958603e-10;
double c11 = 8.100784e-05;
double c02 = -3.747139e-01;
double c30 = -1.016123e-19;
double c21 = -1.234548e-13;
double c12 = -2.324528e-08;
double c03 = 1.891004e-04;
return c10 + c20*2.0*P_ + c11*T_
+ c30*3.0*pow(P_,2.0) + c21*2.0*P_*T_
+ c12*pow(T_,2.0);
}
double h_vdT(const double &P_, const double &T_)
{
double c00 = 1.778741e+06;
double c10 = -6.997339e-02;
double c01 = 2.423675e+03;
double c20 = 1.958603e-10;
double c11 = 8.100784e-05;
double c02 = -3.747139e-01;
double c30 = -1.016123e-19;
double c21 = -1.234548e-13;
double c12 = -2.324528e-08;
double c03 = 1.891004e-04;
return c01 + c11*P_ + c02*2.0*T_
+ c21*pow(P_,2.0) + c12*P_*2.0*T_
+ c03*3.0*pow(T_,2.0);
}
/* Specific enthalpy of liquid (J/kg) in fonction of Pressure (Pa) and Temperature (K) */
double h_l(const double &P_, const double &T_)
{
double c00 = -1.210342e+07;
double c10 = 3.932901e-02;
double c01 = 1.310565e+05;
double c20 = -3.425284e-10;
double c11 = -2.572281e-04;
double c02 = -5.801243e+02;
double c30 = 1.974339e-19;
double c21 = 2.427381e-12;
double c12 = 4.966543e-07;
double c03 = 1.314839e+00;
double c40 = -4.256626e-27;
double c31 = 1.512868e-21;
double c22 = -6.054694e-15;
double c13 = -8.389491e-11;
double c04 = -1.484055e-03;
double c50 = 1.597043e-35;
double c41 = 1.356624e-31;
double c32 = -2.492294e-24;
double c23 = 5.082575e-18;
double c14 = -3.822957e-13;
double c05 = 6.712484e-07;
return c00 + c10*P_ + c01*T_ + c20*pow(P_,2.0)
+ c11*P_*T_ + c02*pow(T_,2.0) + c30*pow(P_,3.0)
+ c21*pow(P_,2.0)*T_ + c12*P_*pow(T_,2.0)
+ c03*pow(T_,3.0) + c40*pow(P_,4.0) + c31*pow(P_,3.0)*T_
+ c22*pow(P_,2.0)*pow(T_,2.0) + c13*P_*pow(T_,3.0)
+ c04*pow(T_,4.0) + c50*pow(P_,5.0) + c41*pow(P_,4.0)*T_
+ c32*pow(P_,3.0)*pow(T_,2.0) + c23*pow(P_,2.0)*pow(T_,3.0)
+ c14*P_*pow(T_,4.0) + c05*pow(T_,5.0);
}
double h_ldP(const double &P_, const double &T_)
{
double c00 = -1.210342e+07;
double c10 = 3.932901e-02;
double c01 = 1.310565e+05;
double c20 = -3.425284e-10;
double c11 = -2.572281e-04;
double c02 = -5.801243e+02;
double c30 = 1.974339e-19;
double c21 = 2.427381e-12;
double c12 = 4.966543e-07;
double c03 = 1.314839e+00;
double c40 = -4.256626e-27;
double c31 = 1.512868e-21;
double c22 = -6.054694e-15;
double c13 = -8.389491e-11;
double c04 = -1.484055e-03;
double c50 = 1.597043e-35;
double c41 = 1.356624e-31;
double c32 = -2.492294e-24;
double c23 = 5.082575e-18;
double c14 = -3.822957e-13;
double c05 = 6.712484e-07;
return c10 + c20*2.0*P_ + c11*T_
+ c30*3.0*pow(P_,2.0)
+ c21*2.0*P_*T_ + c12*pow(T_,2.0)
+ c40*4.0*pow(P_,3.0) + c31*3.0*pow(P_,2.0)*T_
+ c22*2.0*P_*pow(T_,2.0) + c13*pow(T_,3.0)
+ c50*5.0*pow(P_,4.0) + c41*4.0*pow(P_,3.0)*T_
+ c32*3.0*pow(P_,2.0)*pow(T_,2.0) + c23*2.0*P_*pow(T_,3.0)
+ c14*pow(T_,4.0);
}
double h_ldT(const double &P_, const double &T_)
{
double c00 = -1.210342e+07;
double c10 = 3.932901e-02;
double c01 = 1.310565e+05;
double c20 = -3.425284e-10;
double c11 = -2.572281e-04;
double c02 = -5.801243e+02;
double c30 = 1.974339e-19;
double c21 = 2.427381e-12;
double c12 = 4.966543e-07;
double c03 = 1.314839e+00;
double c40 = -4.256626e-27;
double c31 = 1.512868e-21;
double c22 = -6.054694e-15;
double c13 = -8.389491e-11;
double c04 = -1.484055e-03;
double c50 = 1.597043e-35;
double c41 = 1.356624e-31;
double c32 = -2.492294e-24;
double c23 = 5.082575e-18;
double c14 = -3.822957e-13;
double c05 = 6.712484e-07;
return c01 + c11*P_ + c02*2.0*T_ + c21*pow(P_,2.0)
+ c12*P_*2.0*T_ + c03*3.0*pow(T_,2.0)
+ c31*pow(P_,3.0) + c22*pow(P_,2.0)*2.0*T_
+ c13*P_*3.0*pow(T_,2.0) + c04*4.0*pow(T_,3.0)
+ c41*pow(P_,4.0) + c32*pow(P_,3.0)*2.0*T_
+ c23*pow(P_,2.0)*3.0*pow(T_,2.0) + c14*P_*4.0*pow(T_,3.0)
+ c05*5.0*pow(T_,4.0);
}
/* Saturation pressure (Pa) in fonction of Temperature (K)*/
double psat(const double &T_)
{
double c7 = 7.677448367806697e-11;
double c6 = -2.327974895639335e-07;
double c5 = 2.984399245658974e-04;
double c4 = -2.081210501212062e-01;
double c3 = 8.527291155079814e+01;
double c2 = -2.055993982138471e+04;
double c1 = 2.704822454027627e+06;
double c0 = -1.499284498173245e+08;
return c0 + c1*T_ + c2*pow(T_,2.0) + c3*pow(T_,3.0)
+ c4*pow(T_,4.0) + c5*pow(T_,5.0)
+ c6*pow(T_,6.0) + c7*pow(T_,7.0);
}
double psatdT(const double &T_)
{
double c7=7.677448367806697e-11;
double c6=-2.327974895639335e-07;
double c5=2.984399245658974e-04;
double c4=-2.081210501212062e-01;
double c3=8.527291155079814e+01;
double c2=-2.055993982138471e+04;
double c1=2.704822454027627e+06;
double c0=-1.499284498173245e+08;
return c1 + 2.0*c2*T_ + 3.0*c3*pow(T_,2.0)
+ 4.0*c4*pow(T_,3.0) + 5.0*c5*pow(T_,4.0)
+ 6.0*c6*pow(T_,5.0) + 7.0*c7*pow(T_,6.0);
}
/* specific internal energy equation*/
double u(const double &P_, const double &h_, const double &r_)
{
return h_- P_/r_;
}
double udP(const double &P_, const double &h_, const double &r_){
return -1.0/r_;
}
double udh(const double &P_, const double &h_, const double &r_){
return 1.0;
}
double udr(const double &P_, const double &h_, const double &r_){
return P_/pow(r_,2.0);
}
/* volume equation */
double vol(const double &r_, const double &M_){
return M_/r_;
}
double voldr(const double &r_, const double &M_){
return -1.0*M_/pow(r_,2.0);
}
double voldM(const double &r_, const double &M_){
return 1.0/r_;
} | 7,589 | 4,469 |
/*
* Copyright (C) 2012-2014 Brian S O'Neill
* Copyright (C) 2014 Vishal Parakh
*
* 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 _TUPL_LARGEKEYEXCEPTION_HPP
#define _TUPL_LARGEKEYEXCEPTION_HPP
#include "DatabaseError.hpp"
namespace tupl {
/**
* Thrown when a key is too large to fit into a page. Maximum key size is
* defined as: {@code min(16383, (pageSize / 2) - 22)}. When using the default
* page size of 4096 bytes, the maximum key size is 2026 bytes.
*
* @author Brian S O'Neill
* @author Vishal Parakh
*/
class LargeKeyError: public DatabaseError {
public:
LargeKeyError(const size_t /* length */) {
// FIXME: bubble up
// super("Key is too large: " + length);
}
};
}
#endif
| 1,254 | 436 |
#include "Image.h"
namespace uut
{
UUT_OBJECT_IMPLEMENT(Image)
{}
Image::Image()
: _data(nullptr)
{
}
Image::~Image()
{
Destroy();
}
bool Image::Create(const Vector2i& size)
{
if (_size == size)
return true;
Destroy();
_data = SDL_CreateRGBSurface(0,
_size.x, _size.y, 32, 0, 0, 0, 0);
return IsCreated();
}
void Image::Destroy()
{
if (!IsCreated())
return;
SDL_FreeSurface(_data);
_data = nullptr;
}
bool Image::IsCreated() const
{
return _data != nullptr;
}
uintptr_t Image::GetInternalHandle() const
{
return reinterpret_cast<uintptr_t>(_data);
}
} | 611 | 290 |
#include "pic8042contr.hpp"
#include "asm/asmstubs.hpp"
#include "gloxor/modules.hpp"
#include "system/logging.hpp"
// everything is masked on startup
static glox::picContext picCtx{0xFF, 0xFF};
namespace glox::pic
{
void sendEoiSlave()
{
outb(PIC2_COMMAND, PIC_EOI);
}
void sendEoiMaster()
{
outb(PIC1_COMMAND, PIC_EOI);
}
void remap(u8 offset1, u8 offset2)
{
unsigned char a1, a2;
a1 = inb(PIC1_DATA); // save masks
a2 = inb(PIC2_DATA);
outb(PIC1_COMMAND, ICW1_INIT | ICW1_ICW4); // starts the initialization sequence (in cascade mode)
ioWait();
outb(PIC2_COMMAND, ICW1_INIT | ICW1_ICW4);
ioWait();
outb(PIC1_DATA, offset1); // ICW2: Master PIC vector offset
ioWait();
outb(PIC2_DATA, offset2); // ICW2: Slave PIC vector offset
ioWait();
outb(PIC1_DATA, 4); // ICW3: tell Master PIC that there is a slave PIC at IRQ2 (0000 0100)
ioWait();
outb(PIC2_DATA, 2); // ICW3: tell Slave PIC its cascade identity (0000 0010)
ioWait();
outb(PIC1_DATA, ICW4_8086);
ioWait();
outb(PIC2_DATA, ICW4_8086);
ioWait();
outb(PIC1_DATA, a1); // restore saved masks.
outb(PIC2_DATA, a2);
}
void setMasterMask(u8 mask)
{
picCtx.masterMask &= mask;
outb(PIC1_DATA, picCtx.masterMask);
}
void setSlaveMask(u8 mask)
{
picCtx.slaveMask &= mask;
outb(PIC1_DATA, picCtx.slaveMask);
}
} // namespace glox::pic
static void initPic()
{
glox::pic::remap(0x20, 0x28);
gloxDebugLog("Initializing PIC\n");
// Mask all devices
outb(PIC1_DATA, 0xFF);
outb(PIC2_DATA, 0xFF);
}
initDriverCentralModule(initPic); | 1,559 | 764 |
#include "explosion.h"
//////////////////////////////////////////////////////////////////////////////
//
// ExplosionGeo
//
//////////////////////////////////////////////////////////////////////////////
class ExplosionGeoImpl :
public ExplosionGeo
{
private:
//////////////////////////////////////////////////////////////////////////////
//
// Types
//
//////////////////////////////////////////////////////////////////////////////
class ExplosionData : IObject {
public:
TRef<AnimatedImage> m_pimage;
Vector m_position;
Vector m_dposition;
float m_angle;
float m_timeStart;
float m_scale;
};
class ShockwaveData : IObject {
public:
TRef<Image> m_pimageShockwave;
Vector m_position;
Vector m_dposition;
Vector m_forward;
Vector m_right;
Color m_color;
float m_timeStart;
float m_scale;
};
typedef TList<ExplosionData> ExplosionDataList;
//////////////////////////////////////////////////////////////////////////////
//
// Members
//
//////////////////////////////////////////////////////////////////////////////
TList<ShockwaveData> m_listShockwave;
TVector<ExplosionDataList> m_vlistExplosion;
//////////////////////////////////////////////////////////////////////////////
//
// Value Members
//
//////////////////////////////////////////////////////////////////////////////
Number* GetTime() { return Number::Cast(GetChild(0)); }
public:
ExplosionGeoImpl(Number* ptime) :
ExplosionGeo(ptime),
m_vlistExplosion(24)
{
}
//////////////////////////////////////////////////////////////////////////////
//
// Methods
//
//////////////////////////////////////////////////////////////////////////////
void AddExplosion(
const Vector& position,
const Vector& forward,
const Vector& right,
const Vector& dposition,
float radiusExplosion,
float radiusShockWave,
const Color& color,
int countDecals,
TVector<TRef<AnimatedImage> > vpimage,
Image* pimageShockwave
) {
//
// Add the shockwave
//
if (pimageShockwave != NULL) {
m_listShockwave.PushFront();
ShockwaveData& sdata = m_listShockwave.GetFront();
sdata.m_timeStart = GetTime()->GetValue();
sdata.m_pimageShockwave = pimageShockwave;
sdata.m_color = color;
sdata.m_position = position;
sdata.m_dposition = dposition;
sdata.m_scale = radiusShockWave;
sdata.m_forward = forward;
sdata.m_right = right;
}
//
// Add the little explosions
//
int countImage = vpimage.GetCount();
int indexImage = 0;
for (int index = 0; index < countDecals; index++) {
ExplosionDataList& list = m_vlistExplosion.Get(index);
list.PushFront();
ExplosionData& edata = list.GetFront();
edata.m_timeStart = GetTime()->GetValue() + index * 0.25f;
edata.m_pimage = vpimage[indexImage];
edata.m_position = position + Vector::RandomPosition(radiusExplosion * 0.5f);
edata.m_dposition = dposition;
edata.m_angle = random(0, 2 * pi);
edata.m_scale = radiusExplosion;
indexImage++;
if (indexImage >= countImage) {
indexImage = 0;
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Value Methods
//
//////////////////////////////////////////////////////////////////////////////
ZString GetFunctionName() { return "ExplosionGeo"; }
//////////////////////////////////////////////////////////////////////////////
//
// Geometry Methods
//
//////////////////////////////////////////////////////////////////////////////
float RenderShockwaves(Context* pcontext)
{
float fill = 0;
TList<ShockwaveData>::Iterator iter(m_listShockwave);
while (!iter.End()) {
ShockwaveData& sdata = iter.Value();
float time = GetTime()->GetValue() - sdata.m_timeStart;
float bright = 1.0f - time * time;
if (bright <= 0) {
iter.Remove();
} else {
float scale = time * sdata.m_scale;
fill +=
pcontext->DrawDecal(
sdata.m_pimageShockwave->GetSurface(),
bright * sdata.m_color,
sdata.m_position + time * sdata.m_dposition,
scale * sdata.m_forward,
scale * sdata.m_right,
0,
0
);
iter.Next();
}
};
return fill;
}
float RenderExplosions(
Context* pcontext,
ExplosionDataList& list
) {
float fill = 0;
ExplosionDataList::Iterator iter(list);
while (!iter.End()) {
ExplosionData& edata = iter.Value();
float time = GetTime()->GetValue() - edata.m_timeStart;
if (time >= 0) {
int frame = (int)(time * 20.0f);
if (frame >= edata.m_pimage->GetCount()) {
iter.Remove();
continue;
} else {
fill +=
pcontext->DrawDecal(
edata.m_pimage->GetSurface(frame),
Color::White(),
edata.m_position + time * edata.m_dposition,
Vector::GetZero(),
Vector::GetZero(),
edata.m_scale,
edata.m_angle
);
}
}
iter.Next();
}
return fill;
}
void Render(Context* pcontext)
{
float fill = 0;
fill += RenderShockwaves(pcontext);
int count = m_vlistExplosion.GetCount();
for (int index = 0; index < count; index++) {
fill += RenderExplosions(pcontext, m_vlistExplosion.Get(index));
//
// If we have passed the fill limit throw away the rest of the explosions
//
if (fill > 2.0f) {
for (int index2 = index + 1; index2 < count; index2++) {
m_vlistExplosion.Get(index2).SetEmpty();
}
return;
}
}
}
};
//////////////////////////////////////////////////////////////////////////////
//
// ExplosionGeo Factory
//
//////////////////////////////////////////////////////////////////////////////
TRef<ExplosionGeo> CreateExplosionGeo(Number* ptime)
{
return new ExplosionGeoImpl(ptime);
}
| 7,418 | 1,993 |
// Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mediapipe/framework/deps/file_helpers.h"
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <cerrno>
#include "mediapipe/framework/deps/canonical_errors.h"
#include "mediapipe/framework/deps/file_path.h"
#include "mediapipe/framework/deps/status_builder.h"
namespace mediapipe {
namespace file {
::mediapipe::Status GetContents(absl::string_view file_name,
std::string* output) {
FILE* fp = fopen(file_name.data(), "r");
if (fp == NULL) {
return ::mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "Can't find file: " << file_name;
}
output->clear();
while (!feof(fp)) {
char buf[4096];
size_t ret = fread(buf, 1, 4096, fp);
if (ret == 0 && ferror(fp)) {
return ::mediapipe::InternalErrorBuilder(MEDIAPIPE_LOC)
<< "Error while reading file: " << file_name;
}
output->append(std::string(buf, ret));
}
fclose(fp);
return ::mediapipe::OkStatus();
}
::mediapipe::Status SetContents(absl::string_view file_name,
absl::string_view content) {
FILE* fp = fopen(file_name.data(), "w");
if (fp == NULL) {
return ::mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "Can't open file: " << file_name;
}
fwrite(content.data(), sizeof(char), content.size(), fp);
size_t ret = fclose(fp);
if (ret == 0 && ferror(fp)) {
return ::mediapipe::InternalErrorBuilder(MEDIAPIPE_LOC)
<< "Error while writing file: " << file_name;
}
return ::mediapipe::OkStatus();
}
::mediapipe::Status MatchInTopSubdirectories(
const std::string& parent_directory, const std::string& file_name,
std::vector<std::string>* results) {
DIR* dir = opendir(parent_directory.c_str());
CHECK(dir);
// Iterates through the parent direcotry.
while (true) {
struct dirent* dir_ent = readdir(dir);
if (dir_ent == nullptr) {
break;
}
if (std::string(dir_ent->d_name) == "." ||
std::string(dir_ent->d_name) == "..") {
continue;
}
std::string subpath =
JoinPath(parent_directory, std::string(dir_ent->d_name));
DIR* sub_dir = opendir(subpath.c_str());
// Iterates through the subdirecotry to find file matches.
while (true) {
struct dirent* dir_ent_2 = readdir(sub_dir);
if (dir_ent_2 == nullptr) {
break;
}
if (std::string(dir_ent_2->d_name) == "." ||
std::string(dir_ent_2->d_name) == "..") {
continue;
}
if (absl::EndsWith(std::string(dir_ent_2->d_name), file_name)) {
results->push_back(JoinPath(subpath, std::string(dir_ent_2->d_name)));
}
}
closedir(sub_dir);
}
closedir(dir);
return ::mediapipe::OkStatus();
}
::mediapipe::Status Exists(absl::string_view file_name) {
struct stat buffer;
int status;
status = stat(file_name.data(), &buffer);
if (status == 0) {
return ::mediapipe::OkStatus();
}
switch (errno) {
case EACCES:
return ::mediapipe::PermissionDeniedError("Insufficient permissions.");
default:
return ::mediapipe::NotFoundError("The path does not exist.");
}
}
} // namespace file
} // namespace mediapipe
| 3,813 | 1,296 |
#pragma once
#include "PyInstance.hpp"
class PyPythonSubclassInstance : public PyInstance {
public:
typedef PythonSubclass modeled_type;
static void copyConstructFromPythonInstanceConcrete(PythonSubclass* eltType, instance_ptr tgt, PyObject* pyRepresentation, bool isExplicit) {
Type* argType = extractTypeFrom(pyRepresentation->ob_type);
if (argType && argType == eltType) {
eltType->getBaseType()->copy_constructor(tgt, ((PyInstance*)pyRepresentation)->dataPtr());
return;
}
if (argType && argType == eltType->getBaseType()) {
eltType->getBaseType()->copy_constructor(tgt, ((PyInstance*)pyRepresentation)->dataPtr());
return;
}
PyInstance::copyConstructFromPythonInstanceConcrete(eltType, tgt, pyRepresentation, isExplicit);
}
PyObject* tp_getattr_concrete(PyObject* pyAttrName, const char* attrName) {
return specializeForType((PyObject*)this, [&](auto& subtype) {
return subtype.tp_getattr_concrete(pyAttrName, attrName);
}, type()->getBaseType());
}
static bool pyValCouldBeOfTypeConcrete(modeled_type* type, PyObject* pyRepresentation) {
return true;
}
static void constructFromPythonArgumentsConcrete(Type* t, uint8_t* data, PyObject* args, PyObject* kwargs) {
constructFromPythonArguments(data, (Type*)t->getBaseType(), args, kwargs);
}
Py_ssize_t mp_and_sq_length_concrete() {
return specializeForTypeReturningSizeT((PyObject*)this, [&](auto& subtype) {
return subtype.mp_and_sq_length_concrete();
}, type()->getBaseType());
}
};
| 1,664 | 503 |
#include <iostream>
#include "schema.h"
#include "InheritedTypes.hpp"
int main()
{
// const unsigned char encodedState[] = { 0, 0, 205, 244, 1, 1, 205, 32, 3, 193, 1, 0, 204, 200, 1, 205, 44, 1, 2, 166, 80, 108, 97, 121, 101, 114, 193, 2, 0, 100, 1, 204, 150, 2, 163, 66, 111, 116, 3, 204, 200, 193, 3, 213, 2, 3, 100, 193 };
const unsigned char encodedState[] = { 0, 0, 205, 244, 1, 1, 205, 32, 3, 193, 1, 0, 204, 200, 1, 205, 44, 1, 2, 166, 80, 108, 97, 121, 101, 114, 193, 2, 0, 100, 1, 204, 150, 2, 163, 66, 111, 116, 3, 204, 200, 193 };
InheritedTypes *p = new InheritedTypes();
std::cerr << "============ about to decode\n";
p->decode(encodedState, sizeof(encodedState) / sizeof(unsigned char));
std::cerr << "============ decoded ================================================================ \n";
std::cout << "state.entity.x = " << p->entity->x << std::endl;
std::cout << "state.entity.y = " << p->entity->y << std::endl;
std::cout << std::endl;
std::cout << "state.player.name = " << p->player->name << std::endl;
std::cout << "state.player.x = " << p->player->x << std::endl;
std::cout << "state.player.y = " << p->player->y << std::endl;
std::cout << std::endl;
std::cout << "state.bot.name = " << p->bot->name << std::endl;
std::cout << "state.bot.x = " << p->bot->x << std::endl;
std::cout << "state.bot.y = " << p->bot->y << std::endl;
std::cout << "state.bot.power = " << p->bot->power << std::endl;
std::cout << std::endl;
// std::cout << "state.any.power = " << p->any->power << std::endl;
delete p;
return 0;
}
| 1,623 | 801 |
#include <pch.h>
#include <exa/buffered_stream.hpp>
#include <exa/memory_stream.hpp>
#include <exa/concepts.hpp>
using namespace exa;
using namespace testing;
using namespace std::chrono_literals;
namespace
{
auto create_stream(std::shared_ptr<stream> s = std::make_shared<memory_stream>(), std::streamsize bs = 4096)
{
return std::make_shared<buffered_stream>(s, bs);
}
auto create_data(size_t size = 1000)
{
std::vector<uint8_t> v(size, 0);
for (size_t i = 0; i < size; ++i)
{
v[i] = static_cast<uint8_t>(i);
}
return v;
}
struct test_stream : public memory_stream
{
bool seekable = true;
bool writable = true;
bool readable = true;
virtual bool can_seek() const override
{
return seekable;
}
virtual bool can_write() const override
{
return writable;
}
virtual bool can_read() const override
{
return readable;
}
};
struct concurrent_stream : public memory_stream, public lockable<std::mutex>
{
virtual void write(gsl::span<const uint8_t> b) override
{
exa::lock(*this, [&] { memory_stream::write(b); });
}
virtual std::streamsize read(gsl::span<uint8_t> b) override
{
std::streamsize r = 0;
exa::lock(*this, [&] { r = memory_stream::read(b); });
return r;
}
};
struct throw_stream : public memory_stream
{
virtual void write(gsl::span<const uint8_t> b) override
{
throw std::runtime_error("Operation not allowed.");
}
virtual std::streamsize read(gsl::span<uint8_t> b) override
{
throw std::runtime_error("Operation not allowed.");
}
virtual void flush() override
{
throw std::runtime_error("Operation not allowed.");
}
virtual std::streamoff seek(std::streamoff offset, seek_origin origin) override
{
throw std::runtime_error("Operation not allowed.");
}
};
struct tracking_stream : public stream
{
virtual ~tracking_stream() = default;
mutable struct
{
int can_read = 0;
int can_seek = 0;
int can_write = 0;
int size = 0;
int position = 0;
int flush = 0;
int read = 0;
int seek = 0;
int write = 0;
} called;
std::shared_ptr<stream> stream;
tracking_stream(std::shared_ptr<exa::stream> s)
{
stream = s;
}
// Inherited via stream
virtual bool can_read() const override
{
called.can_read += 1;
return stream->can_read();
}
virtual bool can_seek() const override
{
called.can_seek += 1;
return stream->can_seek();
}
virtual bool can_write() const override
{
called.can_write += 1;
return stream->can_write();
}
virtual std::streamsize size() const override
{
called.size += 1;
return stream->size();
}
virtual void size(std::streamsize value) override
{
called.size += 1;
stream->size();
}
virtual std::streamoff position() const override
{
called.position += 1;
return stream->position();
}
virtual void position(std::streamoff value) override
{
called.position += 1;
stream->position();
}
virtual void flush() override
{
called.flush += 1;
stream->flush();
}
virtual std::streamsize read(gsl::span<uint8_t> buffer) override
{
called.read += 1;
return stream->read(buffer);
}
virtual std::streamoff seek(std::streamoff offset, seek_origin origin) override
{
called.seek += 1;
return stream->seek(offset, origin);
}
virtual void write(gsl::span<const uint8_t> buffer) override
{
called.write += 1;
stream->write(buffer);
}
};
}
TEST(buffered_stream_test, concurrent_operations_are_serialized)
{
auto v = create_data();
auto inner = std::make_shared<concurrent_stream>();
auto s = create_stream(inner, 1);
std::array<std::future<void>, 4> tasks;
for (size_t i = 0; i < tasks.size(); ++i)
{
tasks[i] = s->write_async(gsl::span<uint8_t>(v.data() + 250 * i, 250));
}
for (auto& t : tasks)
{
ASSERT_NO_THROW(t.get());
}
s->position(0);
for (size_t i = 0; i < tasks.size(); ++i)
{
auto b = s->read_byte();
ASSERT_TRUE(b == i || b == static_cast<uint8_t>(i + 250) || b == static_cast<uint8_t>(i + 500) ||
b == static_cast<uint8_t>(i + 750));
}
}
TEST(buffered_stream_test, underlying_stream_throws_exception)
{
auto s = create_stream(std::make_shared<throw_stream>());
std::vector<uint8_t> v1(1);
std::vector<uint8_t> v2(10000);
ASSERT_THROW(s->read_async(v1).get(), std::runtime_error);
ASSERT_THROW(s->write_async(v2).get(), std::runtime_error);
s->write_byte(1);
ASSERT_THROW(s->flush_async().get(), std::runtime_error);
}
TEST(buffered_stream_test, copy_to_requires_flushing_of_writes)
{
for (auto async : {false, true})
{
auto s = create_stream();
auto v = create_data();
auto d = std::make_shared<memory_stream>();
s->write(v);
s->position(0);
v[0] = 42;
s->write_byte(42);
d->write_byte(42);
if (async)
{
s->copy_to_async(d).get();
}
else
{
s->copy_to(d);
}
auto r = d->to_array();
ASSERT_THAT(r, ContainerEq(v));
}
}
TEST(buffered_stream_test, copy_to_read_before_copy_copies_all_data)
{
std::vector<std::pair<bool, bool>> data = {{false, false}, {false, true}, {true, false}, {true, true}};
for (auto input : data)
{
auto v = create_data();
auto ts = std::make_shared<test_stream>();
ts->write(v);
ts->position(0);
ts->seekable = input.first;
auto src = create_stream(ts, 100);
src->read_byte();
auto dst = std::make_shared<memory_stream>();
if (input.second)
{
src->copy_to_async(dst).get();
}
else
{
src->copy_to(dst);
}
std::vector<uint8_t> expected(v.size() - 1);
std::copy(std::next(std::begin(v), 1), std::end(v), std::begin(expected));
auto array = dst->to_array();
ASSERT_THAT(array, ContainerEq(expected));
}
}
TEST(buffered_stream_test, should_not_flush_underyling_stream_if_readonly)
{
for (auto can_seek : {true, false})
{
auto underlying = std::make_shared<test_stream>();
underlying->write(create_data(123));
underlying->position(0);
underlying->seekable = can_seek;
underlying->writable = false;
auto tracker = std::make_shared<tracking_stream>(underlying);
auto s = create_stream(tracker);
s->read_byte();
s->flush();
ASSERT_THAT(tracker->called.flush, Eq(0));
s->flush_async().get();
ASSERT_THAT(tracker->called.flush, Eq(0));
}
}
TEST(buffered_stream_test, should_always_flush_underlying_stream_if_writable)
{
std::vector<std::pair<bool, bool>> v = {{true, true}, {true, false}, {false, true}, {false, false}};
for (auto input : v)
{
auto underlying = std::make_shared<test_stream>();
underlying->write(create_data(123));
underlying->position(0);
underlying->readable = input.first;
underlying->seekable = input.second;
underlying->writable = true;
auto tracker = std::make_shared<tracking_stream>(underlying);
auto s = create_stream(tracker);
s->flush();
ASSERT_THAT(tracker->called.flush, Eq(1));
s->flush_async().get();
ASSERT_THAT(tracker->called.flush, Eq(2));
s->write_byte(42);
s->flush();
ASSERT_THAT(tracker->called.flush, Eq(3));
s->flush_async().get();
ASSERT_THAT(tracker->called.flush, Eq(4));
}
}
| 8,561 | 2,758 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include "CommandLineUtils.h"
#include <aws/crt/Api.h>
#include <aws/crt/Types.h>
#include <aws/crt/auth/Credentials.h>
#include <aws/crt/io/Pkcs11.h>
#include <iostream>
namespace Utils
{
CommandLineUtils::CommandLineUtils()
{
// Automatically register the help command
RegisterCommand(m_cmd_help, "", "Prints this message");
}
void CommandLineUtils::RegisterProgramName(Aws::Crt::String newProgramName)
{
m_programName = std::move(newProgramName);
}
void CommandLineUtils::RegisterCommand(CommandLineOption option)
{
if (m_registeredCommands.count(option.m_commandName))
{
fprintf(stdout, "Cannot register command: %s: Command already registered!", option.m_commandName.c_str());
return;
}
m_registeredCommands.insert({option.m_commandName, option});
}
void CommandLineUtils::RegisterCommand(
Aws::Crt::String commandName,
Aws::Crt::String exampleInput,
Aws::Crt::String helpOutput)
{
RegisterCommand(CommandLineOption(commandName, exampleInput, helpOutput));
}
void CommandLineUtils::RemoveCommand(Aws::Crt::String commandName)
{
if (m_registeredCommands.count(commandName))
{
m_registeredCommands.erase(commandName);
}
}
void CommandLineUtils::UpdateCommandHelp(Aws::Crt::String commandName, Aws::Crt::String newCommandHelp)
{
if (m_registeredCommands.count(commandName))
{
m_registeredCommands.at(commandName).m_helpOutput = std::move(newCommandHelp);
}
}
void CommandLineUtils::SendArguments(const char **argv, const char **argc)
{
if (m_beginPosition != nullptr || m_endPosition != nullptr)
{
fprintf(stdout, "Arguments already sent!");
return;
}
m_beginPosition = argv;
m_endPosition = argc;
// Automatically check and print the help message if the help command is present
if (HasCommand(m_cmd_help))
{
PrintHelp();
exit(-1);
}
}
bool CommandLineUtils::HasCommand(Aws::Crt::String command)
{
return std::find(m_beginPosition, m_endPosition, "--" + command) != m_endPosition;
}
Aws::Crt::String CommandLineUtils::GetCommand(Aws::Crt::String command)
{
const char **itr = std::find(m_beginPosition, m_endPosition, "--" + command);
if (itr != m_endPosition && ++itr != m_endPosition)
{
return Aws::Crt::String(*itr);
}
return "";
}
Aws::Crt::String CommandLineUtils::GetCommandOrDefault(Aws::Crt::String command, Aws::Crt::String commandDefault)
{
if (HasCommand(command))
{
return Aws::Crt::String(GetCommand(command));
}
return commandDefault;
}
Aws::Crt::String CommandLineUtils::GetCommandRequired(
Aws::Crt::String command,
Aws::Crt::String optionalAdditionalMessage)
{
if (HasCommand(command))
{
return GetCommand(command);
}
PrintHelp();
fprintf(stderr, "Missing required argument: --%s\n", command.c_str());
if (optionalAdditionalMessage != "")
{
fprintf(stderr, "%s\n", optionalAdditionalMessage.c_str());
}
exit(-1);
}
void CommandLineUtils::PrintHelp()
{
fprintf(stdout, "Usage:\n");
fprintf(stdout, "%s", m_programName.c_str());
for (auto const &pair : m_registeredCommands)
{
fprintf(stdout, " --%s %s", pair.first.c_str(), pair.second.m_exampleInput.c_str());
}
fprintf(stdout, "\n\n");
for (auto const &pair : m_registeredCommands)
{
fprintf(stdout, "* %s:\t\t%s\n", pair.first.c_str(), pair.second.m_helpOutput.c_str());
}
fprintf(stdout, "\n");
}
void CommandLineUtils::AddCommonMQTTCommands()
{
RegisterCommand(m_cmd_endpoint, "<str>", "The endpoint of the mqtt server not including a port.");
RegisterCommand(
m_cmd_ca_file, "<path>", "Path to AmazonRootCA1.pem (optional, system trust store used by default).");
}
void CommandLineUtils::AddCommonProxyCommands()
{
RegisterCommand(m_cmd_proxy_host, "<str>", "Host name of the proxy server to connect through (optional)");
RegisterCommand(
m_cmd_proxy_port, "<int>", "Port of the proxy server to connect through (optional, default='8080'");
}
void CommandLineUtils::AddCommonX509Commands()
{
RegisterCommand(
m_cmd_x509_role, "<str>", "Role alias to use with the x509 credentials provider (required for x509)");
RegisterCommand(m_cmd_x509_endpoint, "<str>", "Endpoint to fetch x509 credentials from (required for x509)");
RegisterCommand(
m_cmd_x509_thing_name, "<str>", "Thing name to fetch x509 credentials on behalf of (required for x509)");
RegisterCommand(
m_cmd_x509_cert_file,
"<path>",
"Path to the IoT thing certificate used in fetching x509 credentials (required for x509)");
RegisterCommand(
m_cmd_x509_key_file,
"<path>",
"Path to the IoT thing private key used in fetching x509 credentials (required for x509)");
RegisterCommand(
m_cmd_x509_ca_file,
"<path>",
"Path to the root certificate used in fetching x509 credentials (required for x509)");
}
void CommandLineUtils::AddCommonTopicMessageCommands()
{
RegisterCommand(
m_cmd_message, "<str>", "The message to send in the payload (optional, default='Hello world!')");
RegisterCommand(m_cmd_topic, "<str>", "Topic to publish, subscribe to. (optional, default='test/topic')");
}
void CommandLineUtils::AddCommonCustomAuthorizerCommands()
{
RegisterCommand(
m_cmd_custom_auth_username,
"<str>",
"The name to send when connecting through the custom authorizer (optional)");
RegisterCommand(
m_cmd_custom_auth_authorizer_name,
"<str>",
"The name of the custom authorizer to connect to (optional but required for everything but custom "
"domains)");
RegisterCommand(
m_cmd_custom_auth_authorizer_signature,
"<str>",
"The signature to send when connecting through a custom authorizer (optional)");
RegisterCommand(
m_cmd_custom_auth_password,
"<str>",
"The password to send when connecting through a custom authorizer (optional)");
}
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildPKCS11MQTTConnection(
Aws::Iot::MqttClient *client)
{
std::shared_ptr<Aws::Crt::Io::Pkcs11Lib> pkcs11Lib =
Aws::Crt::Io::Pkcs11Lib::Create(GetCommandRequired(m_cmd_pkcs11_lib));
if (!pkcs11Lib)
{
fprintf(stderr, "Pkcs11Lib failed: %s\n", Aws::Crt::ErrorDebugString(Aws::Crt::LastError()));
exit(-1);
}
Aws::Crt::Io::TlsContextPkcs11Options pkcs11Options(pkcs11Lib);
pkcs11Options.SetCertificateFilePath(GetCommandRequired(m_cmd_cert_file));
pkcs11Options.SetUserPin(GetCommandRequired(m_cmd_pkcs11_pin));
if (HasCommand(m_cmd_pkcs11_token))
{
pkcs11Options.SetTokenLabel(GetCommand(m_cmd_pkcs11_token));
}
if (HasCommand(m_cmd_pkcs11_slot))
{
uint64_t slotId = std::stoull(GetCommand(m_cmd_pkcs11_slot).c_str());
pkcs11Options.SetSlotId(slotId);
}
if (HasCommand(m_cmd_pkcs11_key))
{
pkcs11Options.SetPrivateKeyObjectLabel(GetCommand(m_cmd_pkcs11_key));
}
Aws::Iot::MqttClientConnectionConfigBuilder clientConfigBuilder(pkcs11Options);
if (!clientConfigBuilder)
{
fprintf(
stderr,
"MqttClientConnectionConfigBuilder failed: %s\n",
Aws::Crt::ErrorDebugString(Aws::Crt::LastError()));
exit(-1);
}
if (HasCommand(m_cmd_ca_file))
{
clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str());
}
if (HasCommand(m_cmd_port_override))
{
int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str());
if (tmp_port > 0 && tmp_port < UINT16_MAX)
{
clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port));
}
}
clientConfigBuilder.WithEndpoint(GetCommandRequired(m_cmd_endpoint));
return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder);
}
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildWebsocketX509MQTTConnection(
Aws::Iot::MqttClient *client)
{
Aws::Crt::Io::TlsContext x509TlsCtx;
Aws::Iot::MqttClientConnectionConfigBuilder clientConfigBuilder;
std::shared_ptr<Aws::Crt::Auth::ICredentialsProvider> provider = nullptr;
Aws::Crt::Io::TlsContextOptions tlsCtxOptions = Aws::Crt::Io::TlsContextOptions::InitClientWithMtls(
GetCommandRequired(m_cmd_x509_cert_file).c_str(), GetCommandRequired(m_cmd_x509_key_file).c_str());
if (!tlsCtxOptions)
{
fprintf(
stderr,
"Unable to initialize tls context options, error: %s!\n",
Aws::Crt::ErrorDebugString(tlsCtxOptions.LastError()));
exit(-1);
}
if (HasCommand(m_cmd_x509_ca_file))
{
tlsCtxOptions.OverrideDefaultTrustStore(nullptr, GetCommand(m_cmd_x509_ca_file).c_str());
}
x509TlsCtx = Aws::Crt::Io::TlsContext(tlsCtxOptions, Aws::Crt::Io::TlsMode::CLIENT);
if (!x509TlsCtx)
{
fprintf(
stderr,
"Unable to create tls context, error: %s!\n",
Aws::Crt::ErrorDebugString(x509TlsCtx.GetInitializationError()));
exit(-1);
}
Aws::Crt::Auth::CredentialsProviderX509Config x509Config;
x509Config.TlsOptions = x509TlsCtx.NewConnectionOptions();
if (!x509Config.TlsOptions)
{
fprintf(
stderr,
"Unable to create tls options from tls context, error: %s!\n",
Aws::Crt::ErrorDebugString(x509Config.TlsOptions.LastError()));
exit(-1);
}
x509Config.Endpoint = GetCommandRequired(m_cmd_x509_endpoint);
x509Config.RoleAlias = GetCommandRequired(m_cmd_x509_role);
x509Config.ThingName = GetCommandRequired(m_cmd_x509_thing_name);
Aws::Crt::Http::HttpClientConnectionProxyOptions proxyOptions;
if (HasCommand(m_cmd_proxy_host))
{
proxyOptions = GetProxyOptionsForMQTTConnection();
x509Config.ProxyOptions = proxyOptions;
}
provider = Aws::Crt::Auth::CredentialsProvider::CreateCredentialsProviderX509(x509Config);
if (!provider)
{
fprintf(stderr, "Failure to create credentials provider!\n");
exit(-1);
}
Aws::Iot::WebsocketConfig config(GetCommandRequired(m_cmd_signing_region), provider);
clientConfigBuilder = Aws::Iot::MqttClientConnectionConfigBuilder(config);
if (HasCommand(m_cmd_ca_file))
{
clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str());
}
if (HasCommand(m_cmd_proxy_host))
{
clientConfigBuilder.WithHttpProxyOptions(proxyOptions);
}
if (HasCommand(m_cmd_port_override))
{
int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str());
if (tmp_port > 0 && tmp_port < UINT16_MAX)
{
clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port));
}
}
clientConfigBuilder.WithEndpoint(GetCommandRequired(m_cmd_endpoint));
return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder);
}
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildWebsocketMQTTConnection(
Aws::Iot::MqttClient *client)
{
Aws::Crt::Io::TlsContext x509TlsCtx;
Aws::Iot::MqttClientConnectionConfigBuilder clientConfigBuilder;
std::shared_ptr<Aws::Crt::Auth::ICredentialsProvider> provider = nullptr;
Aws::Crt::Auth::CredentialsProviderChainDefaultConfig defaultConfig;
provider = Aws::Crt::Auth::CredentialsProvider::CreateCredentialsProviderChainDefault(defaultConfig);
if (!provider)
{
fprintf(stderr, "Failure to create credentials provider!\n");
exit(-1);
}
Aws::Iot::WebsocketConfig config(GetCommandRequired(m_cmd_signing_region), provider);
clientConfigBuilder = Aws::Iot::MqttClientConnectionConfigBuilder(config);
if (HasCommand(m_cmd_ca_file))
{
clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str());
}
if (HasCommand(m_cmd_proxy_host))
{
clientConfigBuilder.WithHttpProxyOptions(GetProxyOptionsForMQTTConnection());
}
if (HasCommand(m_cmd_port_override))
{
int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str());
if (tmp_port > 0 && tmp_port < UINT16_MAX)
{
clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port));
}
}
clientConfigBuilder.WithEndpoint(GetCommandRequired(m_cmd_endpoint));
return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder);
}
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildDirectMQTTConnection(
Aws::Iot::MqttClient *client)
{
Aws::Crt::String certificatePath = GetCommandRequired(m_cmd_cert_file);
Aws::Crt::String keyPath = GetCommandRequired(m_cmd_key_file);
Aws::Crt::String endpoint = GetCommandRequired(m_cmd_endpoint);
auto clientConfigBuilder =
Aws::Iot::MqttClientConnectionConfigBuilder(certificatePath.c_str(), keyPath.c_str());
clientConfigBuilder.WithEndpoint(endpoint);
if (HasCommand(m_cmd_ca_file))
{
clientConfigBuilder.WithCertificateAuthority(GetCommand(m_cmd_ca_file).c_str());
}
if (HasCommand(m_cmd_proxy_host))
{
clientConfigBuilder.WithHttpProxyOptions(GetProxyOptionsForMQTTConnection());
}
if (HasCommand(m_cmd_port_override))
{
int tmp_port = atoi(GetCommand(m_cmd_port_override).c_str());
if (tmp_port > 0 && tmp_port < UINT16_MAX)
{
clientConfigBuilder.WithPortOverride(static_cast<uint16_t>(tmp_port));
}
}
return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder);
}
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildDirectMQTTConnectionWithCustomAuthorizer(
Aws::Iot::MqttClient *client)
{
Aws::Crt::String auth_username = GetCommandOrDefault(m_cmd_custom_auth_username, "");
Aws::Crt::String auth_authorizer_name = GetCommandOrDefault(m_cmd_custom_auth_authorizer_name, "");
Aws::Crt::String auth_authorizer_signature = GetCommandOrDefault(m_cmd_custom_auth_authorizer_signature, "");
Aws::Crt::String auth_password = GetCommandOrDefault(m_cmd_custom_auth_password, "");
Aws::Crt::String endpoint = GetCommandRequired(m_cmd_endpoint);
auto clientConfigBuilder = Aws::Iot::MqttClientConnectionConfigBuilder::NewDefaultBuilder();
clientConfigBuilder.WithEndpoint(endpoint);
clientConfigBuilder.WithCustomAuthorizer(
auth_username, auth_authorizer_name, auth_authorizer_signature, auth_password);
return GetClientConnectionForMQTTConnection(client, &clientConfigBuilder);
}
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::BuildMQTTConnection()
{
if (!m_internal_client)
{
m_internal_client = Aws::Iot::MqttClient();
if (!m_internal_client)
{
fprintf(
stderr,
"MQTT Client Creation failed with error %s\n",
Aws::Crt::ErrorDebugString(m_internal_client.LastError()));
exit(-1);
}
}
if (HasCommand(m_cmd_pkcs11_lib))
{
return BuildPKCS11MQTTConnection(&m_internal_client);
}
else if (HasCommand(m_cmd_signing_region))
{
if (HasCommand(m_cmd_x509_endpoint))
{
return BuildWebsocketX509MQTTConnection(&m_internal_client);
}
else
{
return BuildWebsocketMQTTConnection(&m_internal_client);
}
}
else if (HasCommand(m_cmd_custom_auth_authorizer_name))
{
return BuildDirectMQTTConnectionWithCustomAuthorizer(&m_internal_client);
}
else
{
return BuildDirectMQTTConnection(&m_internal_client);
}
}
Aws::Crt::Http::HttpClientConnectionProxyOptions CommandLineUtils::GetProxyOptionsForMQTTConnection()
{
Aws::Crt::Http::HttpClientConnectionProxyOptions proxyOptions;
proxyOptions.HostName = GetCommand(m_cmd_proxy_host);
int ProxyPort = atoi(GetCommandOrDefault(m_cmd_proxy_port, "8080").c_str());
if (ProxyPort > 0 && ProxyPort < UINT16_MAX)
{
proxyOptions.Port = static_cast<uint16_t>(ProxyPort);
}
else
{
proxyOptions.Port = 8080;
}
proxyOptions.AuthType = Aws::Crt::Http::AwsHttpProxyAuthenticationType::None;
return proxyOptions;
}
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> CommandLineUtils::GetClientConnectionForMQTTConnection(
Aws::Iot::MqttClient *client,
Aws::Iot::MqttClientConnectionConfigBuilder *clientConfigBuilder)
{
auto clientConfig = clientConfigBuilder->Build();
if (!clientConfig)
{
fprintf(
stderr,
"Client Configuration initialization failed with error %s\n",
Aws::Crt::ErrorDebugString(clientConfig.LastError()));
exit(-1);
}
auto connection = client->NewConnection(clientConfig);
if (!*connection)
{
fprintf(
stderr,
"MQTT Connection Creation failed with error %s\n",
Aws::Crt::ErrorDebugString(connection->LastError()));
exit(-1);
}
return connection;
}
void CommandLineUtils::SampleConnectAndDisconnect(
std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> connection,
Aws::Crt::String clientId)
{
/*
* In a real world application you probably don't want to enforce synchronous behavior
* but this is a sample console application, so we'll just do that with a condition variable.
*/
std::promise<bool> connectionCompletedPromise;
std::promise<void> connectionClosedPromise;
/*
* This will execute when an mqtt connect has completed or failed.
*/
auto onConnectionCompleted =
[&](Aws::Crt::Mqtt::MqttConnection &, int errorCode, Aws::Crt::Mqtt::ReturnCode returnCode, bool) {
if (errorCode)
{
fprintf(stdout, "Connection failed with error %s\n", Aws::Crt::ErrorDebugString(errorCode));
connectionCompletedPromise.set_value(false);
}
else
{
fprintf(stdout, "Connection completed with return code %d\n", returnCode);
connectionCompletedPromise.set_value(true);
}
};
auto onInterrupted = [&](Aws::Crt::Mqtt::MqttConnection &, int error) {
fprintf(stdout, "Connection interrupted with error %s\n", Aws::Crt::ErrorDebugString(error));
};
auto onResumed = [&](Aws::Crt::Mqtt::MqttConnection &, Aws::Crt::Mqtt::ReturnCode, bool) {
fprintf(stdout, "Connection resumed\n");
};
/*
* Invoked when a disconnect message has completed.
*/
auto onDisconnect = [&](Aws::Crt::Mqtt::MqttConnection &) {
fprintf(stdout, "Disconnect completed\n");
connectionClosedPromise.set_value();
};
connection->OnConnectionCompleted = std::move(onConnectionCompleted);
connection->OnDisconnect = std::move(onDisconnect);
connection->OnConnectionInterrupted = std::move(onInterrupted);
connection->OnConnectionResumed = std::move(onResumed);
/*
* Actually perform the connect dance.
*/
fprintf(stdout, "Connecting...\n");
if (!connection->Connect(clientId.c_str(), false /*cleanSession*/, 1000 /*keepAliveTimeSecs*/))
{
fprintf(
stderr, "MQTT Connection failed with error %s\n", Aws::Crt::ErrorDebugString(connection->LastError()));
exit(-1);
}
// wait for the OnConnectionCompleted callback to fire, which sets connectionCompletedPromise...
if (connectionCompletedPromise.get_future().get() == false)
{
fprintf(stderr, "Connection failed\n");
exit(-1);
}
/* Disconnect */
if (connection->Disconnect())
{
connectionClosedPromise.get_future().wait();
}
}
} // namespace Utils
| 22,108 | 6,622 |
// -*- mode: C++; tab-width: 4; c-basic-offset: 4 -*-
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)
#define WINDOWS
#else
#define POSIX
#endif
#include <sstream> // ostringstream
#ifdef WINDOWS
#include "windows.h"
#else
#include <errno.h>
#endif
#include "system_error.h"
namespace image {
using namespace std;
system_error::system_error(
const char * function_name) throw () :
#ifdef WINDOWS
error_code_(::GetLastError()),
#else
error_code_(errno),
#endif
function_name_(function_name)
{}
system_error::system_error(
int error_code,
const char * function_name) throw () :
error_code_(error_code),
function_name_(function_name)
{}
const char * system_error::what() const throw ()
{
#ifdef WINDOWS
return "system_error";
#else
return ::strerror(error_code_);
#endif
}
string system_error::message() const
{
ostringstream oss;
oss << "In function `" << function_name_ << "':" << std::endl
<< "System error " << error_code_ << ": ";
#ifdef WINDOWS
LPVOID buffer;
::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
0,
error_code_,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
static_cast<LPSTR>(&buffer),
0,
0);
oss << static_cast<LPCSTR>(buffer);
::LocalFree(buffer);
#else
oss << what();
#endif
return oss.str();
}
}
| 1,788 | 642 |
/*!
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
*/
#include <gtest/gtest.h>
#include "answer.hpp"
#include "samples.hpp"
#include <pyclustering/cluster/pam_build.hpp>
#include <pyclustering/utils/metric.hpp>
using namespace pyclustering;
using namespace pyclustering::clst;
using namespace pyclustering::utils::metric;
void template_pam_build_medoids(const dataset_ptr & p_data,
const std::size_t p_amount,
const medoids & p_expected,
const data_t p_data_type,
const distance_metric<point> & p_metric = distance_metric_factory<point>::euclidean_square())
{
dataset data;
if (p_data_type == data_t::POINTS) {
data = *p_data;
}
else {
distance_matrix(*p_data, data);
}
medoids medoids;
pam_build(p_amount, p_metric).initialize(data, p_data_type, medoids);
ASSERT_EQ(p_amount, medoids.size());
ASSERT_EQ(p_expected, medoids);
}
TEST(utest_pam_build, correct_medoids_simple_01) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_simple_01_distance_matrix) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX);
}
TEST(utest_pam_build, correct_medoids_simple_01_wrong_amount_1) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1, { 4 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_simple_01_wrong_amount_3) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 3, { 4, 8, 0 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_simple_01_wrong_amount_10) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 10, { 4, 8, 0, 9, 1, 7, 6, 5, 2, 3 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_simple_01_metrics) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::euclidean_square());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::euclidean());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::manhattan());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::chebyshev());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::POINTS, distance_metric_factory<point>::minkowski(2.0));
}
TEST(utest_pam_build, correct_medoids_simple_01_metrics_distance_matrix) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::euclidean_square());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::euclidean());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::manhattan());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::chebyshev());
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 2, { 4, 8 }, data_t::DISTANCE_MATRIX, distance_metric_factory<point>::minkowski(2.0));
}
TEST(utest_pam_build, correct_medoids_simple_02) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_02), 3, { 3, 20, 14 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_simple_03) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_03), 4, { 28, 56, 5, 34 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_simple_04) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_04), 5, { 44, 7, 64, 25, 55 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_one_dimensional) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 2, { 0, 20 }, data_t::POINTS);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 1, { 0 }, data_t::POINTS);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 3, { 0, 20, 1 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_one_dimensional_distance_matrix) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 2, { 0, 20 }, data_t::DISTANCE_MATRIX);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 1, { 0 }, data_t::DISTANCE_MATRIX);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 3, { 0, 20, 1 }, data_t::DISTANCE_MATRIX);
}
TEST(utest_pam_build, correct_medoids_three_dimensional) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 2, { 15, 4 }, data_t::POINTS);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 1, { 15 }, data_t::POINTS);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 3, { 15, 4, 14 }, data_t::POINTS);
}
TEST(utest_pam_build, correct_medoids_three_dimensional_distance_matrix) {
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 2, { 15, 4 }, data_t::DISTANCE_MATRIX);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 1, { 15 }, data_t::DISTANCE_MATRIX);
template_pam_build_medoids(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 3, { 15, 4, 14 }, data_t::DISTANCE_MATRIX);
}
| 6,721 | 2,906 |
#include "segment.cpp"
#include "is_intersect_ss.cpp"
#include "distance_sp.cpp"
namespace geometry {
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D
Real distance_ss(const Segment &a, const Segment &b) {
if(is_intersect_ss(a, b)) return 0;
return min({distance_sp(a, b.a), distance_sp(a, b.b), distance_sp(b, a.a), distance_sp(b, a.b)});
}
}
| 379 | 162 |
/*[DirectX9]*/
matrix MVP;
int filterMin = 2;
int filterMag = 2;
int filterMip = 2;
texture texture1;
float4 textChannel;
sampler sampler1 = sampler_state
{
Texture = <texture1>;
MinFilter = POINT;
MagFilter = POINT;
MipFilter = POINT;
};
struct VInput{
float4 Pos : POSITION;
float3 Normal : Normal;
float4 Color : COLOR0;
float2 uv : TEXCOORD0;
};
struct VOutput{
float4 Pos : POSITION;
float2 uv : TEXCOORD0;
float4 Color : TEXCOORD1;
float3 channel : TEXCOORD2;
};
VOutput Vshader(VInput input)
{
VOutput output;
output.Pos = mul(input.Pos, MVP);
output.Color = input.Color;
output.uv = input.uv;
output.channel = input.Normal;
return output;
}
float4 Pshader(VOutput output) : COLOR0
{
float4 ret = output.Color;
float3 temp = tex2D(sampler1, output.uv).xyz;// * output.channel;
float f = (temp.x + temp.y + temp.z);
ret.xyz *= f;
ret.a *= f;
return ret;
}
technique main
{
pass P
{
VertexShader = compile vs_2_0 Vshader();
PixelShader = compile ps_2_0 Pshader();
}
}
/*[/DirectX9]*/
/*[OpenglES_Vertex]*/
//attribute in
attribute vec4 inPosition;
attribute vec2 inTexcoord;
attribute vec4 inColor;
//
uniform mat4 MVP;
varying vec2 passCoord;
varying vec4 passColor0;
void main()
{
passCoord = inTexcoord;
passColor0 = vec4(inColor.b, inColor.g, inColor.r, inColor.a);
gl_Position = MVP * inPosition;
}
/*[/OpenglES_Vertex]*/
/*[OpenglES_Pixel]*/
precision lowp float;
varying vec4 passColor0;
varying vec2 passCoord;
uniform sampler2D texture1;
uniform vec3 textChannel;
void main()
{
vec3 v = texture2D(texture1, passCoord).xyz * textChannel;
float f = (v.x+v.y+v.z);
gl_FragColor = vec4(f*passColor0.xyz, f*passColor0.a*255.0);
}
/*[/OpenglES_Pixel]*/
| 1,725 | 784 |
//q10082v2.cpp - 2011/09/09
//10082 - WERTYU
//accepted at
//run time = 0.012
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
char ch[]={'`','1','2','3','4','5','6','7','8','9','0','-','=',
'Q','W','E','R','T','Y','U','I','O','P','[',']','\\',
'A','S','D','F','G','H','J','K','L',';','\'',
'Z','X','C','V','B','N','M',',','.','/'};
int maxLeng = 0;
char inputChar[10000] = {0};
int i = 0, j = 0;
while(gets(inputChar)!=NULL){
maxLeng = strlen(inputChar);
for(i=0;i<maxLeng;i++){
if(inputChar[i]==' '){
printf(" ");
}else{
for(j=0;j<strlen(ch);j++){
if(inputChar[i]==ch[j]){
printf("%c", ch[j-1]);
break;
}
}
}
}
printf("\n");
}
return 0;
}
| 806 | 421 |
/*******************************************************************\
Module: Traces of GOTO Programs
Author: Daniel Kroening
Date: July 2005
\*******************************************************************/
#include <cassert>
#include <util/threeval.h>
#include <util/simplify_expr.h>
#include <util/arith_tools.h>
#include <solvers/prop/prop_conv.h>
#include <solvers/prop/prop.h>
#include "partial_order_concurrency.h"
#include "build_goto_trace.h"
/*******************************************************************\
Function: build_full_lhs_rec
Inputs:
Outputs:
Purpose:
\*******************************************************************/
exprt build_full_lhs_rec(
const prop_convt &prop_conv,
const namespacet &ns,
const exprt &src_original, // original identifiers
const exprt &src_ssa) // renamed identifiers
{
if(src_ssa.id()!=src_original.id())
return src_original;
const irep_idt id=src_original.id();
if(id==ID_index)
{
// get index value from src_ssa
exprt index_value=prop_conv.get(to_index_expr(src_ssa).index());
if(index_value.is_not_nil())
{
simplify(index_value, ns);
index_exprt tmp=to_index_expr(src_original);
tmp.index()=index_value;
tmp.array()=
build_full_lhs_rec(prop_conv, ns,
to_index_expr(src_original).array(),
to_index_expr(src_ssa).array());
return tmp;
}
return src_original;
}
else if(id==ID_member)
{
member_exprt tmp=to_member_expr(src_original);
tmp.struct_op()=build_full_lhs_rec(
prop_conv, ns,
to_member_expr(src_original).struct_op(),
to_member_expr(src_ssa).struct_op());
}
else if(id==ID_if)
{
if_exprt tmp2=to_if_expr(src_original);
tmp2.false_case()=build_full_lhs_rec(prop_conv, ns,
tmp2.false_case(), to_if_expr(src_ssa).false_case());
tmp2.true_case()=build_full_lhs_rec(prop_conv, ns,
tmp2.true_case(), to_if_expr(src_ssa).true_case());
exprt tmp=prop_conv.get(to_if_expr(src_ssa).cond());
if(tmp.is_true())
return tmp2.true_case();
else if(tmp.is_false())
return tmp2.false_case();
else
return tmp2;
}
else if(id==ID_typecast)
{
typecast_exprt tmp=to_typecast_expr(src_original);
tmp.op()=build_full_lhs_rec(prop_conv, ns,
to_typecast_expr(src_original).op(), to_typecast_expr(src_ssa).op());
return tmp;
}
else if(id==ID_byte_extract_little_endian ||
id==ID_byte_extract_big_endian)
{
exprt tmp=src_original;
assert(tmp.operands().size()==2);
tmp.op0()=build_full_lhs_rec(prop_conv, ns, tmp.op0(), src_ssa.op0());
// re-write into big case-split
}
return src_original;
}
/*******************************************************************\
Function: adjust_lhs_object
Inputs:
Outputs:
Purpose:
\*******************************************************************/
exprt adjust_lhs_object(
const prop_convt &prop_conv,
const namespacet &ns,
const exprt &src)
{
return nil_exprt();
}
/*******************************************************************\
Function: build_goto_trace
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void build_goto_trace_backup(
const symex_target_equationt &target,
const prop_convt &prop_conv,
const namespacet &ns,
goto_tracet &goto_trace)
{
// We need to re-sort the steps according to their clock.
// Furthermore, read-events need to occur before write
// events with the same clock.
typedef std::map<mp_integer, goto_tracet::stepst> time_mapt;
time_mapt time_map;
mp_integer current_time=0;
for(symex_target_equationt::SSA_stepst::const_iterator
it=target.SSA_steps.begin();
it!=target.SSA_steps.end();
it++)
{
const symex_target_equationt::SSA_stept &SSA_step=*it;
if(prop_conv.l_get(SSA_step.guard_literal)!=tvt(true))
continue;
if(it->is_constraint() ||
it->is_spawn())
continue;
else if(it->is_atomic_begin())
{
// for atomic sections the timing can only be determined once we see
// a shared read or write (if there is none, the time will be
// reverted to the time before entering the atomic section); we thus
// use a temporary negative time slot to gather all events
current_time*=-1;
continue;
}
else if(it->is_shared_read() || it->is_shared_write() ||
it->is_atomic_end())
{
mp_integer time_before=current_time;
if(it->is_shared_read() || it->is_shared_write())
{
// these are just used to get the time stamp
exprt clock_value=prop_conv.get(
symbol_exprt(partial_order_concurrencyt::rw_clock_id(it)));
to_integer(clock_value, current_time);
}
else if(it->is_atomic_end() && current_time<0)
current_time*=-1;
assert(current_time>=0);
// move any steps gathered in an atomic section
if(time_before<0)
{
time_mapt::iterator entry=
time_map.insert(std::make_pair(
current_time,
goto_tracet::stepst())).first;
entry->second.splice(entry->second.end(), time_map[time_before]);
time_map.erase(time_before);
}
continue;
}
// drop hidden assignments
if(it->is_assignment() &&
SSA_step.assignment_type!=symex_target_equationt::STATE)
continue;
goto_tracet::stepst &steps=time_map[current_time];
steps.push_back(goto_trace_stept());
goto_trace_stept &goto_trace_step=steps.back();
goto_trace_step.thread_nr=SSA_step.source.thread_nr;
goto_trace_step.pc=SSA_step.source.pc;
goto_trace_step.comment=SSA_step.comment;
goto_trace_step.lhs_object=SSA_step.original_lhs_object;
goto_trace_step.type=SSA_step.type;
goto_trace_step.format_string=SSA_step.format_string;
goto_trace_step.io_id=SSA_step.io_id;
goto_trace_step.formatted=SSA_step.formatted;
goto_trace_step.identifier=SSA_step.identifier;
if(SSA_step.original_full_lhs.is_not_nil())
goto_trace_step.full_lhs=
build_full_lhs_rec(
prop_conv, ns, SSA_step.original_full_lhs, SSA_step.ssa_full_lhs);
if(SSA_step.ssa_lhs.is_not_nil())
goto_trace_step.lhs_object_value=prop_conv.get(SSA_step.ssa_lhs);
if(SSA_step.ssa_full_lhs.is_not_nil())
{
goto_trace_step.full_lhs_value=prop_conv.get(SSA_step.ssa_full_lhs);
simplify(goto_trace_step.full_lhs_value, ns);
}
for(std::list<exprt>::const_iterator
j=SSA_step.converted_io_args.begin();
j!=SSA_step.converted_io_args.end();
j++)
{
const exprt &arg=*j;
if(arg.is_constant() ||
arg.id()==ID_string_constant)
goto_trace_step.io_args.push_back(arg);
else
{
exprt tmp=prop_conv.get(arg);
goto_trace_step.io_args.push_back(tmp);
}
}
if(SSA_step.is_assert() ||
SSA_step.is_assume())
{
goto_trace_step.cond_expr=SSA_step.cond_expr;
goto_trace_step.cond_value=
prop_conv.l_get(SSA_step.cond_literal).is_true();
}
else if(SSA_step.is_location() &&
SSA_step.source.pc->is_goto())
{
goto_trace_step.cond_expr=SSA_step.source.pc->guard;
const bool backwards=SSA_step.source.pc->is_backwards_goto();
symex_target_equationt::SSA_stepst::const_iterator next=it;
++next;
assert(next!=target.SSA_steps.end());
// goto was taken if backwards and next is enabled or forward
// and next is not active;
// there is an ambiguity here if a forward goto is to the next
// instruction, which we simply ignore for now
goto_trace_step.goto_taken=
backwards==
(prop_conv.l_get(next->guard_literal)==tvt(true));
}
}
// Now assemble into a single goto_trace.
// This expoits sorted-ness of the map.
for(time_mapt::iterator t_it=time_map.begin();
t_it!=time_map.end(); t_it++)
{
goto_trace.steps.splice(goto_trace.steps.end(), t_it->second);
}
// produce the step numbers
unsigned step_nr=0;
for(goto_tracet::stepst::iterator
s_it=goto_trace.steps.begin();
s_it!=goto_trace.steps.end();
s_it++)
s_it->step_nr=++step_nr;
// Now delete anything after failed assertion
for(goto_tracet::stepst::iterator
s_it1=goto_trace.steps.begin();
s_it1!=goto_trace.steps.end();
s_it1++)
if(s_it1->is_assert() && !s_it1->cond_value)
{
s_it1++;
for(goto_tracet::stepst::iterator
s_it2=s_it1;
s_it2!=goto_trace.steps.end();
s_it2=goto_trace.steps.erase(s_it2));
break;
}
}
/*******************************************************************\
Function: build_goto_trace
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void build_goto_trace(
const symex_target_equationt &target,
const prop_convt &prop_conv,
const namespacet &ns,
goto_tracet &goto_trace)
{
// We need to re-sort the steps according to their clock.
// Furthermore, read-events need to occur before write
// events with the same clock.
for(symex_target_equationt::SSA_stepst::const_iterator
it=target.SSA_steps.begin();
it!=target.SSA_steps.end();
it++)
{
const symex_target_equationt::SSA_stept &SSA_step=*it;
if(prop_conv.l_get(SSA_step.guard_literal)!=tvt(true))
continue;
if(it->is_constraint() || it->is_spawn())
continue;
// drop hidden assignments
if(it->is_assignment() && SSA_step.assignment_type!=symex_target_equationt::STATE)
continue;
goto_tracet::stepst &steps=goto_trace.steps;
steps.push_back(goto_trace_stept());
goto_trace_stept &goto_trace_step=steps.back();
goto_trace_step.thread_nr=SSA_step.source.thread_nr;
goto_trace_step.pc=SSA_step.source.pc;
goto_trace_step.comment=SSA_step.comment;
goto_trace_step.lhs_object=SSA_step.original_lhs_object;
goto_trace_step.type=SSA_step.type;
goto_trace_step.format_string=SSA_step.format_string;
goto_trace_step.io_id=SSA_step.io_id;
goto_trace_step.formatted=SSA_step.formatted;
goto_trace_step.identifier=SSA_step.identifier;
if(SSA_step.original_full_lhs.is_not_nil())
goto_trace_step.full_lhs=
build_full_lhs_rec(
prop_conv, ns, SSA_step.original_full_lhs, SSA_step.ssa_full_lhs);
if(SSA_step.ssa_lhs.is_not_nil())
goto_trace_step.lhs_object_value=prop_conv.get(SSA_step.ssa_lhs);
if(SSA_step.ssa_full_lhs.is_not_nil())
{
goto_trace_step.full_lhs_value=prop_conv.get(SSA_step.ssa_full_lhs);
simplify(goto_trace_step.full_lhs_value, ns);
}
for(std::list<exprt>::const_iterator
j=SSA_step.converted_io_args.begin();
j!=SSA_step.converted_io_args.end();
j++)
{
const exprt &arg=*j;
if(arg.is_constant() ||
arg.id()==ID_string_constant)
goto_trace_step.io_args.push_back(arg);
else
{
exprt tmp=prop_conv.get(arg);
goto_trace_step.io_args.push_back(tmp);
}
}
if(SSA_step.is_assert() ||
SSA_step.is_assume())
{
goto_trace_step.cond_expr=SSA_step.cond_expr;
goto_trace_step.cond_value=
prop_conv.l_get(SSA_step.cond_literal).is_true();
}
else if(SSA_step.is_location() &&
SSA_step.source.pc->is_goto())
{
goto_trace_step.cond_expr=SSA_step.source.pc->guard;
const bool backwards=SSA_step.source.pc->is_backwards_goto();
symex_target_equationt::SSA_stepst::const_iterator next=it;
++next;
assert(next!=target.SSA_steps.end());
// goto was taken if backwards and next is enabled or forward
// and next is not active;
// there is an ambiguity here if a forward goto is to the next
// instruction, which we simply ignore for now
goto_trace_step.goto_taken=
backwards==
(prop_conv.l_get(next->guard_literal)==tvt(true));
}
}
// produce the step numbers
unsigned step_nr=0;
for(goto_tracet::stepst::iterator
s_it=goto_trace.steps.begin();
s_it!=goto_trace.steps.end();
s_it++)
s_it->step_nr=++step_nr;
// Now delete anything after failed assertion
/* for(goto_tracet::stepst::iterator
s_it1=goto_trace.steps.begin();
s_it1!=goto_trace.steps.end();
s_it1++)
if(s_it1->is_assert() && !s_it1->cond_value)
{
s_it1++;
for(goto_tracet::stepst::iterator
s_it2=s_it1;
s_it2!=goto_trace.steps.end();
s_it2=goto_trace.steps.erase(s_it2));
break;
}*/
}
| 12,800 | 4,698 |
//
// Created by Daniel Brotman on 2019-02-21.
//
#include <sigmf.h>
#include <flatbuffers_json_visitor.h>
#include <iostream>
#include <fstream>
#include <ctype.h>
int main(int argc, char *argv[]) {
json master;
for(int i=2; i < argc; i++){
std::ifstream fp(argv[i]);
if(i==2){
fp >> master;
}
else {
json j;
fp >> j;
for(auto &anno : j["annotations"]){
master["annotations"].push_back(anno);
}
}
fp.close();
}
std::ofstream mp(argv[1]);
mp << master.dump(4) << std::endl;
mp.close();
} | 647 | 241 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <cmath>
#include <new>
#include <vector>
#include "services/prediction/proximity_info_factory.h"
#include "services/prediction/touch_position_correction.h"
// NOTE: This class has been translated to C++ and modified from the Android
// Open Source Project. Specifically from some functions of the following file:
// https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/
// android-5.1.1_r8/java/src/com/android/inputmethod/keyboard/ProximityInfo.java
namespace prediction {
const float ProximityInfoFactory::SEARCH_DISTANCE = 1.2f;
const float ProximityInfoFactory::DEFAULT_TOUCH_POSITION_CORRECTION_RADIUS =
0.15f;
// Hardcoded qwerty keyboard proximity settings
ProximityInfoFactory::ProximityInfoFactory() {
plocale_ = "en";
pgrid_width_ = 32;
pgrid_height_ = 16;
pgrid_size_ = pgrid_width_ * pgrid_height_;
pcell_width_ = (348 + pgrid_width_ - 1) / pgrid_width_;
pcell_height_ = (174 + pgrid_height_ - 1) / pgrid_height_;
pkeyboard_min_width_ = 348;
pkeyboard_height_ = 174;
pmost_common_key_height_ = 29;
pmost_common_key_width_ = 58;
}
ProximityInfoFactory::~ProximityInfoFactory() {
}
latinime::ProximityInfo* ProximityInfoFactory::GetNativeProximityInfo() {
const int default_width = pmost_common_key_width_;
const int threshold = (int)(default_width * SEARCH_DISTANCE);
const int threshold_squared = threshold * threshold;
const int last_pixel_x_coordinate = pgrid_width_ * pcell_width_ - 1;
const int last_pixel_y_coordinate = pgrid_height_ * pcell_height_ - 1;
std::vector<Key> pgrid_neighbors[32 * 16 /*pgrid_size_*/];
int neighbor_count_per_cell[pgrid_size_];
std::fill_n(neighbor_count_per_cell, pgrid_size_, 0);
Key neighbors_flat_buffer[32 * 16 * 26 /*pgrid_size_ * keyset::key_count*/];
const int half_cell_width = pcell_width_ / 2;
const int half_cell_height = pcell_height_ / 2;
for (int i = 0; i < keyset::key_count; i++) {
const Key key = keyset::key_set[i];
const int key_x = key.kx;
const int key_y = key.ky;
const int top_pixel_within_threshold = key_y - threshold;
const int y_delta_to_grid = top_pixel_within_threshold % pcell_height_;
const int y_middle_of_top_cell =
top_pixel_within_threshold - y_delta_to_grid + half_cell_height;
const int y_start =
std::max(half_cell_height,
y_middle_of_top_cell +
(y_delta_to_grid <= half_cell_height ? 0 : pcell_height_));
const int y_end =
std::min(last_pixel_y_coordinate, key_y + key.kheight + threshold);
const int left_pixel_within_threshold = key_x - threshold;
const int x_delta_to_grid = left_pixel_within_threshold % pcell_width_;
const int x_middle_of_left_cell =
left_pixel_within_threshold - x_delta_to_grid + half_cell_width;
const int x_start =
std::max(half_cell_width,
x_middle_of_left_cell +
(x_delta_to_grid <= half_cell_width ? 0 : pcell_width_));
const int x_end =
std::min(last_pixel_x_coordinate, key_x + key.kwidth + threshold);
int base_index_of_current_row =
(y_start / pcell_height_) * pgrid_width_ + (x_start / pcell_width_);
for (int center_y = y_start; center_y <= y_end; center_y += pcell_height_) {
int index = base_index_of_current_row;
for (int center_x = x_start; center_x <= x_end;
center_x += pcell_width_) {
if (SquaredDistanceToEdge(center_x, center_y, key) <
threshold_squared) {
neighbors_flat_buffer[index * keyset::key_count +
neighbor_count_per_cell[index]] =
keyset::key_set[i];
++neighbor_count_per_cell[index];
}
++index;
}
base_index_of_current_row += pgrid_width_;
}
}
for (int i = 0; i < pgrid_size_; ++i) {
const int index_start = i * keyset::key_count;
const int index_end = index_start + neighbor_count_per_cell[i];
for (int index = index_start; index < index_end; index++) {
pgrid_neighbors[i].push_back(neighbors_flat_buffer[index]);
}
}
int proximity_chars_array[pgrid_size_ * MAX_PROXIMITY_CHARS_SIZE];
for (int i = 0; i < pgrid_size_; i++) {
int info_index = i * MAX_PROXIMITY_CHARS_SIZE;
for (int j = 0; j < neighbor_count_per_cell[i]; j++) {
Key neighbor_key = pgrid_neighbors[i][j];
proximity_chars_array[info_index] = neighbor_key.kcode;
info_index++;
}
}
int key_x_coordinates[keyset::key_count];
int key_y_coordinates[keyset::key_count];
int key_widths[keyset::key_count];
int key_heights[keyset::key_count];
int key_char_codes[keyset::key_count];
float sweet_spot_center_xs[keyset::key_count];
float sweet_spot_center_ys[keyset::key_count];
float sweet_spot_radii[keyset::key_count];
for (int key_index = 0; key_index < keyset::key_count; key_index++) {
Key key = keyset::key_set[key_index];
key_x_coordinates[key_index] = key.kx;
key_y_coordinates[key_index] = key.ky;
key_widths[key_index] = key.kwidth;
key_heights[key_index] = key.kheight;
key_char_codes[key_index] = key.kcode;
}
TouchPositionCorrection touch_position_correction;
if (touch_position_correction.IsValid()) {
const int rows = touch_position_correction.GetRows();
const float default_radius =
DEFAULT_TOUCH_POSITION_CORRECTION_RADIUS *
(float)std::hypot(pmost_common_key_width_, pmost_common_key_height_);
for (int key_index = 0; key_index < keyset::key_count; key_index++) {
Key key = keyset::key_set[key_index];
sweet_spot_center_xs[key_index] =
(key.khit_box_left + key.khit_box_right) * 0.5f;
sweet_spot_center_ys[key_index] =
(key.khit_box_top + key.khit_box_bottom) * 0.5f;
sweet_spot_radii[key_index] = default_radius;
const int row = key.khit_box_top / pmost_common_key_height_;
if (row < rows) {
const int hit_box_width = key.khit_box_right - key.khit_box_left;
const int hit_box_height = key.khit_box_bottom - key.khit_box_top;
const float hit_box_diagonal =
(float)std::hypot(hit_box_width, hit_box_height);
sweet_spot_center_xs[key_index] +=
touch_position_correction.GetX(row) * hit_box_width;
sweet_spot_center_ys[key_index] +=
touch_position_correction.GetY(row) * hit_box_height;
sweet_spot_radii[key_index] =
touch_position_correction.GetRadius(row) * hit_box_diagonal;
}
}
}
latinime::ProximityInfo* proximity_info = new latinime::ProximityInfo(
plocale_, pkeyboard_min_width_, pkeyboard_height_, pgrid_width_,
pgrid_height_, pmost_common_key_width_, pmost_common_key_height_,
proximity_chars_array, pgrid_size_ * MAX_PROXIMITY_CHARS_SIZE,
keyset::key_count, key_x_coordinates, key_y_coordinates, key_widths,
key_heights, key_char_codes, sweet_spot_center_xs, sweet_spot_center_ys,
sweet_spot_radii);
return proximity_info;
}
int ProximityInfoFactory::SquaredDistanceToEdge(int x, int y, Key k) {
const int left = k.kx;
const int right = left + k.kwidth;
const int top = k.ky;
const int bottom = top + k.kheight;
const int edge_x = x < left ? left : (x > right ? right : x);
const int edge_y = y < top ? top : (y > bottom ? bottom : y);
const int dx = x - edge_x;
const int dy = y - edge_y;
return dx * dx + dy * dy;
}
} // namespace prediction
| 7,647 | 2,824 |
//
// Created by chen-tian on 17-7-19.
//
#include <iostream>
#include <fstream>
using namespace std;
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <Eigen/Geometry>
#include <boost/format.hpp>
//字符串格式化
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
int main(int argc, char** argv){
vector<cv::Mat> colorImgs, depthImgs;
vector<Eigen::Isometry3d> poses;
ifstream f("../pose.txt");//f is name
if (!f)
{
cerr<<"please run this program with pose.txt"<<endl;
return 1;
}
for (int i=0; i<5; i++)
{
//boost::format to format the srting
boost::format fmt("../%s/%d.%s");//the format of the image
colorImgs.push_back(cv::imread( (fmt%"color"%(i+1)%"png").str() ));
depthImgs.push_back(cv::imread( (fmt%"depth"%(i+1)%"pgm").str() ,-1 ));//-1 is used to read initial image
double data[7] = {0};
for (auto& d:data )
f>>d;
Eigen::Quaterniond q(data[6], data[3], data[4], data[5] );//the last number is the real
Eigen::Isometry3d T(q);//euler 4*4
T.pretranslate(Eigen::Vector3d( data[0], data[1], data[2] ));
poses.push_back(T);
}
//K
double cx=325.5;
double cy=253.5;
double fx=518.0;
double fy=519.0;
double depthScale=100.0;
cout<<"transfering image to point clouds..."<<endl;
//point clouds typedef: XYZRGB
typedef pcl::PointXYZRGB PointT;
typedef pcl::PointCloud<PointT> PointCloud;
PointCloud::Ptr pointCloud(new PointCloud);
for (int i=0; i<5; i++)
{
cout<<"transfering..."<<i+1<<endl;
cv::Mat color = colorImgs[i];
cv::Mat depth = depthImgs[i];
Eigen::Isometry3d T = poses[i];
for(int v=0; v<color.rows;v++)
for(int u=0; u<color.cols;u++)
{
unsigned int d = depth.ptr<unsigned short>(v)[u];
if (d==0)continue;
Eigen::Vector3d point;
point[2] = double(d)/depthScale;
point[0] = (u-cx)*point[2]/fx;
point[1] = (v-cy)*point[2]/fy;
Eigen::Vector3d pointWorld = T*point;
PointT p;
p.x = pointWorld[0];
p.y = pointWorld[1];
p.z = pointWorld[2];
p.b = color.data[v*color.step+u*color.channels()];
p.g = color.data[v*color.step+u*color.channels()+1];
p.r = color.data[v*color.step+u*color.channels()+2];
pointCloud->points.push_back(p);
}
}
pointCloud->is_dense = false;
cout<<"pointcloud has "<<pointCloud->size()<<" points"<<endl;
pcl::io::savePCDFileBinary("map.pcd", *pointCloud);
}
| 2,808 | 1,053 |
//
// Created by 86759 on 2022-01-14.
//
#include "SegmentRegister.h"
#include "SystemAddressRegister.h"
segment_descriptor_t load_descriptor(uint32_t value) {
uint32_t descriptor_index = value >> 3;
uint32_t offset = descriptor_index * 64/8;
const auto address = SystemAddressRegister::GDT + offset;
const auto descriptor = (uint64_t)*address;
segment_descriptor_t segment_descriptor;
segment_descriptor.base =
((descriptor & 0x1111'0000'0000'0000) >> 48 << 0) +
((descriptor & 0x0000'0000'0000'0011) >> 0 << 15) +
((descriptor & 0x0000'0000'1100'0000) >> 24 << 23) +
0;
segment_descriptor.limit =
((descriptor & 0x0000'1111'0000'0000) >> 32 << 0) +
((descriptor & 0x0000'0000'0000'0011) >> 16 << 15) +
0;
// TODO: set remain bits
}
uint16_t SegmentRegister::CS_r = 0xF000;
uint16_t SegmentRegister::SS_r = 0x0000;
uint16_t SegmentRegister::DS_r = 0x0000;
uint16_t SegmentRegister::ES_r = 0x0000;
uint16_t SegmentRegister::FS_r = 0x0000;
uint16_t SegmentRegister::GS_r = 0x0000;
segment_descriptor_t SegmentRegister::CS_descriptor;
segment_descriptor_t SegmentRegister::SS_descriptor;
segment_descriptor_t SegmentRegister::DS_descriptor;
segment_descriptor_t SegmentRegister::ES_descriptor;
segment_descriptor_t SegmentRegister::FS_descriptor;
segment_descriptor_t SegmentRegister::GS_descriptor;
uint16_t SegmentRegister::CS() { return CS_r; }
uint16_t SegmentRegister::SS() { return SS_r; }
uint16_t SegmentRegister::DS() { return DS_r; }
uint16_t SegmentRegister::ES() { return ES_r; }
uint16_t SegmentRegister::FS() { return FS_r; }
uint16_t SegmentRegister::GS() { return GS_r; }
void SegmentRegister::CS(uint16_t value) { CS_r = value; CS_descriptor = load_descriptor(value); }
void SegmentRegister::SS(uint16_t value) { SS_r = value; SS_descriptor = load_descriptor(value); }
void SegmentRegister::DS(uint16_t value) { DS_r = value; DS_descriptor = load_descriptor(value); }
void SegmentRegister::ES(uint16_t value) { ES_r = value; ES_descriptor = load_descriptor(value); }
void SegmentRegister::FS(uint16_t value) { FS_r = value; FS_descriptor = load_descriptor(value); }
void SegmentRegister::GS(uint16_t value) { GS_r = value; GS_descriptor = load_descriptor(value); }
| 2,356 | 961 |
#include "cheats.hpp"
#include "Helpers/Address.hpp"
namespace CTRPluginFramework {
//Fish Byte Always
void FishAlwaysBiteRightAway(MenuEntry *entry) {
static const Address fishbite(0x1EA844, 0x1EA288, 0x1EA864, 0x1EA864, 0x1EA7A0, 0x1EA7A0, 0x1EA76C, 0x1EA76C);
if(entry->WasJustActivated())
Process::Patch(fishbite.addr, 0xE3A0005A);
else if(!entry->IsActivated())
Process::Patch(fishbite.addr, 0xE0800100);
}
//Fish Can't Be Scared
void FishCantBeScared(MenuEntry *entry) {
static const Address fishscare(0x1EAB14, 0x1EA558, 0x1EAB34, 0x1EAB34, 0x1EAA70, 0x1EAA70, 0x1EAA3C, 0x1EAA3C);
if(entry->WasJustActivated())
Process::Patch(fishscare.addr, 0xE3500001);
else if(!entry->IsActivated())
Process::Patch(fishscare.addr, 0xE3500000);
}
}
| 796 | 423 |
#include <iostream>
using namespace std;
int main(){
string str;
cin>>str;
for (int i = 0; i < str.length(); i++)
{
if(i % 3 == 2){
cout<<"..*.";
}else{
cout<<"..#.";
}
}
cout<<".\n";
for (int i = 0; i < str.length(); i++)
{
if(i % 3 == 2){
cout<<".*.*";
}else{
cout<<".#.#";
}
}cout<<".\n";
// 3rd line;
for (int i = 0; i < str.length(); i++)
{
if(i % 3 == 2){
cout<<"*."<<str[i]<<".";
}else{
if(i!=0){
if((i-1)%3 == 2){
cout<<"*";
}
else{
cout<<"#";
}
}
else{
cout<<"#";
}
cout<<"."<<str[i]<<".";
}
}
if(str.length()%3 == 0){
cout<<"*\n";
}
else{
cout<<"#\n";
}
// 3rd line ends
for (int i = 0; i < str.length(); i++)
{
if(i % 3 == 2){
cout<<".*.*";
}else{
cout<<".#.#";
}
}
cout<<".\n";
for (int i = 0; i < str.length(); i++)
{
if(i % 3 == 2){
cout<<"..*.";
}else{
cout<<"..#.";
}
}
cout<<".\n";
return 0;
} | 1,300 | 507 |
/* The MIT License
Copyright (c) 2013 Adrian Tan <atks@umich.edu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "index.h"
namespace
{
class Igor : Program
{
public:
///////////
//options//
///////////
std::string input_vcf_file;
kstring_t output_vcf_index_file;
bool print;
Igor(int argc, char **argv)
{
version = "0.5";
//////////////////////////
//options initialization//
//////////////////////////
try
{
std::string desc = "Indexes a VCF.GZ or BCF file.";
TCLAP::CmdLine cmd(desc, ' ', version);
VTOutput my;
cmd.setOutput(&my);
TCLAP::SwitchArg arg_print("p", "p", "print options and summary []", cmd, false);
TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);
cmd.parse(argc, argv);
input_vcf_file = arg_input_vcf_file.getValue();
print = arg_print.getValue();
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
abort();
}
};
void initialize()
{
}
void index()
{
htsFile *file = hts_open(input_vcf_file.c_str(), "r");
if (file==NULL)
{
exit(1);
}
htsFormat ftype = file->format;
if (ftype.compression!=bgzf&&ftype.format!=vcf&&ftype.format!=bcf)
{
fprintf(stderr, "[%s:%d %s] Not a BGZF VCF/BCF file: %s\n", __FILE__, __LINE__, __FUNCTION__, input_vcf_file.c_str());
exit(1);
}
int32_t min_shift;
output_vcf_index_file = {0,0,0};
int32_t ret;
if (ftype.format==bcf)
{
kputs(input_vcf_file.c_str(), &output_vcf_index_file);
kputs(".csi", &output_vcf_index_file);
min_shift = 14;
ret = bcf_index_build(input_vcf_file.c_str(), min_shift);
}
else if (ftype.format==vcf)
{
kputs(input_vcf_file.c_str(), &output_vcf_index_file);
kputs(".tbi", &output_vcf_index_file);
min_shift = 0;
tbx_conf_t conf = tbx_conf_vcf;
ret = tbx_index_build(input_vcf_file.c_str(), min_shift, &conf);
}
if (ret)
{
exit(1);
}
};
void print_options()
{
if (!print) return;
std::clog << "index v" << version << "\n\n";
std::clog << "options: input VCF file " << input_vcf_file << "\n";
std::clog << " output index file " << output_vcf_index_file.s << "\n";
std::clog << "\n";
}
void print_stats()
{
};
~Igor() {};
private:
};
}
bool index(int argc, char ** argv)
{
Igor igor(argc, argv);
igor.print_options();
igor.initialize();
igor.index();
igor.print_stats();
return igor.print;
}; | 4,065 | 1,407 |
#include <Set>
#include <Map>
#include <List>
#include <String>
#include <FStream>
using namespace std;
#include "Book.h"
#include "Customer.h"
#include "Library.h"
int Book::MaxBookId = 0;
Book::Book(void) {
// Empty.
}
Book::Book(const string& author, const string& title)
:m_bookId(++MaxBookId),
m_author(author),
m_title(title) {
// Empty.
}
/*
Book::Book(const Book& book)
:m_bookId(book.m_bookId),
m_author(book.m_author),
m_title(book.m_title),
m_borrowed(book.m_borrowed),
m_customerId(book.m_customerId),
m_reservationList(book.m_reservationList) {
// Empty.
}
Book& Book::operator=(const Book& book) {
m_bookId = book.m_bookId;
m_author = book.m_author;
m_title = book.m_title;
m_borrowed = book.m_borrowed;
m_customerId = book.m_customerId;
m_reservationList = book.m_reservationList;
return *this;
}
*/
void Book::read(ifstream& inStream) {
inStream.read((char*) &m_bookId, sizeof m_bookId);
getline(inStream, m_author);
getline(inStream, m_title);
inStream.read((char*)&m_borrowed, sizeof m_borrowed);
inStream.read((char*) &m_customerId, sizeof m_customerId);
{ int reserveListSize;
inStream.read((char*) &reserveListSize,
sizeof reserveListSize);
for (int count = 0; count < reserveListSize; ++count) {
int customerId;
inStream.read((char*) &customerId, sizeof customerId);
m_reservationList.push_back(customerId);
}
}
}
void Book::write(ofstream& outStream) const {
outStream.write((char*) &m_bookId, sizeof m_bookId);
outStream << m_author << endl;
outStream << m_title << endl;
outStream.write((char*)&m_borrowed, sizeof m_borrowed);
outStream.write((char*) &m_customerId, sizeof m_customerId);
{ int reserveListSize = m_reservationList.size();
outStream.write((char*) &reserveListSize,
sizeof reserveListSize);
for (int customerId : m_reservationList) {
outStream.write((char*) &customerId, sizeof customerId);
}
}
}
void Book::borrowBook(int customerId) {
m_borrowed = true;
m_customerId = customerId;
}
int Book::reserveBook(int customerId) {
m_reservationList.push_back(customerId);
return m_reservationList.size();
}
void Book::returnBook() {
m_borrowed = false;
}
void Book::unreserveBook(int customerId) {
m_reservationList.remove(customerId);
}
ostream& operator<<(ostream& outStream, const Book& book) {
outStream << "\"" << book.m_title << "\" by " << book.m_author;
if (book.m_borrowed) {
outStream << endl << " Borrowed by: "
<< Library::s_customerMap[book.m_customerId].name()
<< ".";
}
if (!book.m_reservationList.empty()) {
outStream << endl << " Reserved by: ";
bool first = true;
for (int customerId : book.m_reservationList) {
outStream << (first ? "" : ",")
<< Library::s_customerMap[customerId].name();
first = false;
}
outStream << ".";
}
return outStream;
} | 2,983 | 1,089 |
/*
** EPITECH PROJECT, 2021
** R-TYPE
** File description:
** Created by stun3r,
*/
#ifndef SERVER_HPP
#define SERVER_HPP
#include "Room/Room.hpp"
class Server {
public:
Server();
~Server();
void run();
void startReceive();
void refresh();
private:
void handleReceive(const boost::system::error_code &, std::size_t);
void handleSend(std::shared_ptr<std::string>, const boost::system::error_code &, std::size_t);
bool hasRoom(const std::string &);
Room *getRoomsByName(const std::string &) const;
void createRoom(const boost::property_tree::ptree &);
void joinRoom(const boost::property_tree::ptree &);
void destroyRoom(const boost::property_tree::ptree &);
void listRoom(const boost::property_tree::ptree &);
void roomReceive(const boost::property_tree::ptree &);
std::set<Room *> _rooms;
boost::asio::io_service _ioservice;
std::shared_ptr<boost::asio::ip::udp::socket> _socket;
boost::asio::ip::udp::endpoint _endpoint;
std::array<char, 128> _buffer;
std::map<std::string, std::function<void(const boost::property_tree::ptree &)>> _command;
};
#endif //SERVER_HPP
| 1,107 | 423 |
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <string>
#include <SFML/Graphics.hpp>
#include <ResourceManager/ResourceManager.hpp>
#include <Map/TileIsoHexa.hpp>
namespace cfg
{
class Config
{
Config() = delete;
Config(const Config&) = delete;
Config& operator=(const Config&) = delete;
public:
static std::string tex_path;
static std::string map_path;
static sf::Font font;
static rm::ResourceManager<std::string,sf::Texture> textureManager;
static sf::Vector2i mapMoussPosition;
static map::TileIsoHexa moussCursorTile;
static sf::Texture moussCursorTex;
static sf::Sprite moussCursorSpr;
static void clear();
static void drawCursor(sf::RenderWindow& target,sf::RenderStates states = sf::RenderStates::Default);
};
};
#endif
| 860 | 266 |
/*
* djnn v2
*
* The copyright holders for the contents of this file are:
* Ecole Nationale de l'Aviation Civile, France (2018-2019)
* See file "license.terms" for the rights and conditions
* defined by copyright holders.
*
*
* Contributors:
* Mathieu Magnaudet <mathieu.magnaudet@enac.fr>
* Stephane Conversy <stephane.conversy@enac.fr>
*
*/
#include <stdexcept>
#include "double_property.h"
#include "core/serializer/serializer.h"
#include "core/utils/error.h"
#include "core/utils/djnn_dynamic_cast.h"
#if !defined(DJNN_NO_DEBUG) || !defined(DJNN_NO_SERIALIZE)
#include "core/utils/iostream.h"
#endif
namespace djnn
{
double
getDouble (CoreProcess* p)
{
DoubleProperty *dp = djnn_dynamic_cast<DoubleProperty*> (p);
if (dp != nullptr)
return dp->get_value();
else
warning (p, "getDouble only works on double properties");
return 0;
}
void
setDouble (CoreProcess* p, double v)
{
DoubleProperty *dp = djnn_dynamic_cast<DoubleProperty*> (p);
if (dp != nullptr)
dp->set_value(v, true);
else
warning (p, "setDouble only works on double properties");
}
void
AbstractDoubleProperty::set_value (int v, bool propagate)
{
set_value((double)v, propagate);
}
void
AbstractDoubleProperty::set_value (double v, bool propagate)
{
get_ref_value() = v;
if (is_activable () && propagate) {
notify_activation ();
notify_parent ();
}
}
void
AbstractDoubleProperty::set_value (bool v, bool propagate)
{
set_value((double)(v ? 1 : 0), propagate);
}
void
AbstractDoubleProperty::set_value (const string& v, bool propagate)
{
double oldVal = get_value();
try {
if (!v.empty ()) {
set_value((double)stof (v), propagate);
}
}
catch (const std::invalid_argument& ia) {
get_ref_value() = oldVal;
warning (this, "failed to convert the string \"" + v + "\" into a double property value\n");
}
}
void
AbstractDoubleProperty::set_value (CoreProcess* v, bool propagate)
{
warning (this, "undefined conversion from Process to Double\n");
}
#ifndef DJNN_NO_DEBUG
void
AbstractDoubleProperty::dump (int level)
{
loginfonofl ( (get_parent () ? get_parent ()->find_child_name(this) : get_name ()) + " [ " + get_string_value() + " ]");
//std::cout << (get_parent () ? get_parent ()->find_child_name(this) : get_name ()) << " [ " << get_value() << " ]";
}
#endif
#ifndef DJNN_NO_SERIALIZE
void
AbstractDoubleProperty::serialize (const djnn::string& format) {
AbstractSerializer::pre_serialize(this, format);
AbstractSerializer::serializer->start ("core:doubleproperty");
AbstractSerializer::serializer->text_attribute ("id", get_name ());
AbstractSerializer::serializer->float_attribute ("value", get_value ());
AbstractSerializer::serializer->end ();
AbstractSerializer::post_serialize(this);
}
#endif
DoubleProperty*
DoubleProperty::impl_clone (map<CoreProcess*, CoreProcess*>& origs_clones)
{
auto res = new DoubleProperty (nullptr, get_name (), get_value());
origs_clones[this] = res;
return res;
}
DoublePropertyProxy*
DoublePropertyProxy::impl_clone (map<CoreProcess*, CoreProcess*>& origs_clones)
{
auto res = new DoublePropertyProxy (nullptr, get_name (), get_ref_value());
origs_clones[this] = res;
return res;
}
}
| 3,421 | 1,181 |
#include "LED.h"
LED::LED(int number){
this->number = number;
// much easier with C++11 using to_string(number)
ostringstream s; // using a stream to contruct the path
s << LED_PATH << number; //append LED number to LED_PATH
path = string(s.str()); //convert back from stream to string
}
void LED::writeLED(string filename, string value){
ofstream fs;
fs.open((path + filename).c_str());
fs << value;
fs.close();
}
void LED::removeTrigger(){
writeLED("/trigger", "none");
}
void LED::turnOn(){
cout << "Turning LED" << number << " on." << endl;
removeTrigger();
writeLED("/brightness", "1");
}
void LED::turnOff(){
cout << "Turning LED" << number << " off." << endl;
removeTrigger();
writeLED("/brightness", "0");
}
void LED::flash(string delayms = "50"){
cout << "Making LED" << number << " flash." << endl;
writeLED("/trigger", "timer");
writeLED("/delay_on", delayms);
writeLED("/delay_off", delayms);
}
void LED::outputState(){
ifstream fs;
fs.open( (path + "/trigger").c_str());
string line;
while(getline(fs,line)) cout << line << endl;
fs.close();
}
LED::~LED(){
cout << "destroying the LED with path: " << path << endl;
}
| 1,224 | 414 |
/*******************************************************************************
* Copyright (c) 2014, 2016 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#ifndef JITBUILDER_ILGENERATOR_METHOD_DETAILS_INCL
#define JITBUILDER_ILGENERATOR_METHOD_DETAILS_INCL
/*
* The following #define and typedef must appear before any #includes in this file
*/
#ifndef JITBUILDER_ILGENERATOR_METHOD_DETAILS_CONNECTOR
#define JITBUILDER_ILGENERATOR_METHOD_DETAILS_CONNECTOR
namespace JitBuilder { class IlGeneratorMethodDetails; }
namespace JitBuilder { typedef ::JitBuilder::IlGeneratorMethodDetails IlGeneratorMethodDetailsConnector; }
#endif // !defined(JITBUILDER_ILGENERATOR_METHOD_DETAILS_CONNECTOR)
#include "ilgen/OMRIlGeneratorMethodDetails.hpp"
#include "infra/Annotations.hpp"
#include "env/IO.hpp"
class TR_InlineBlocks;
class TR_ResolvedMethod;
class TR_IlGenerator;
namespace TR { class Compilation; }
namespace TR { class ResolvedMethod; }
namespace TR { class ResolvedMethodSymbol; }
namespace TR { class SymbolReferenceTable; }
namespace JitBuilder
{
class ResolvedMethod;
class OMR_EXTENSIBLE IlGeneratorMethodDetails : public OMR::IlGeneratorMethodDetailsConnector
{
public:
IlGeneratorMethodDetails() :
OMR::IlGeneratorMethodDetailsConnector(),
_method(NULL)
{ }
IlGeneratorMethodDetails(TR::ResolvedMethod *method) :
OMR::IlGeneratorMethodDetailsConnector(),
_method(method)
{ }
IlGeneratorMethodDetails(TR_ResolvedMethod *method);
TR::ResolvedMethod * getMethod() { return _method; }
TR_ResolvedMethod * getResolvedMethod() { return (TR_ResolvedMethod *)_method; }
bool sameAs(TR::IlGeneratorMethodDetails & other, TR_FrontEnd *fe);
void print(TR_FrontEnd *fe, TR::FILE *file);
virtual TR_IlGenerator *getIlGenerator(TR::ResolvedMethodSymbol *methodSymbol,
TR_FrontEnd * fe,
TR::Compilation *comp,
TR::SymbolReferenceTable *symRefTab,
bool forceClassLookahead,
TR_InlineBlocks *blocksToInline);
protected:
TR::ResolvedMethod * _method;
};
}
#endif // defined(JITBUILDER_ILGENERATOR_METHOD_DETAILS_INCL)
| 3,351 | 1,012 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
#include "h265_sps_scc_extension_parser.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "h265_common.h"
#include "rtc_base/arraysize.h"
#include "rtc_base/bit_buffer.h"
namespace h265nal {
class H265SpsSccExtensionParserTest : public ::testing::Test {
public:
H265SpsSccExtensionParserTest() {}
~H265SpsSccExtensionParserTest() override {}
};
TEST_F(H265SpsSccExtensionParserTest, TestSampleSpsSccExtension) {
// sps_scc_extension
// fuzzer::conv: data
const uint8_t buffer[] = {0x80};
// fuzzer::conv: begin
auto sps_scc_extension = H265SpsSccExtensionParser::ParseSpsSccExtension(
buffer, arraysize(buffer), /* sps->chroma_format_idc */ 1,
/* sps->bit_depth_luma_minus8 */ 0, /* sps->bit_depth_chroma_minus8 */ 0);
// fuzzer::conv: end
EXPECT_TRUE(sps_scc_extension != nullptr);
EXPECT_EQ(1, sps_scc_extension->sps_curr_pic_ref_enabled_flag);
EXPECT_EQ(0, sps_scc_extension->palette_mode_enabled_flag);
EXPECT_EQ(0, sps_scc_extension->palette_max_size);
EXPECT_EQ(0, sps_scc_extension->delta_palette_max_predictor_size);
EXPECT_EQ(0,
sps_scc_extension->sps_palette_predictor_initializers_present_flag);
EXPECT_EQ(0,
sps_scc_extension->sps_num_palette_predictor_initializers_minus1);
EXPECT_EQ(0, sps_scc_extension->sps_palette_predictor_initializers.size());
EXPECT_EQ(0, sps_scc_extension->motion_vector_resolution_control_idc);
EXPECT_EQ(0, sps_scc_extension->intra_boundary_filtering_disabled_flag);
}
} // namespace h265nal
| 1,587 | 665 |
/*
* abstract_comm.hpp
*
* Created on: 2014/05/17
* Author: ueno
*/
#ifndef ABSTRACT_COMM_HPP_
#define ABSTRACT_COMM_HPP_
#ifdef PROFILE_REGIONS
extern int current_fold;
#endif
#include <limits.h>
#include "utils.hpp"
#include "fiber.hpp"
#define debug(...) debug_print(ABSCO, __VA_ARGS__)
class AlltoallBufferHandler {
public:
virtual ~AlltoallBufferHandler() { }
virtual void* get_buffer() = 0;
virtual void add(void* buffer, void* data, int offset, int length) = 0;
virtual void* clear_buffers() = 0;
virtual void* second_buffer() = 0;
virtual int max_size() = 0;
virtual int buffer_length() = 0;
virtual MPI_Datatype data_type() = 0;
virtual int element_size() = 0;
virtual void received(void* buf, int offset, int length, int from) = 0;
virtual void finish() = 0;
};
class AsyncAlltoallManager {
struct Buffer {
void* ptr;
int length;
};
struct PointerData {
void* ptr;
int length;
int64_t header;
};
struct CommTarget {
CommTarget()
: reserved_size_(0)
, filled_size_(0) {
cur_buf.ptr = NULL;
cur_buf.length = 0;
pthread_mutex_init(&send_mutex, NULL);
}
~CommTarget() {
pthread_mutex_destroy(&send_mutex);
}
pthread_mutex_t send_mutex;
// monitor : send_mutex
volatile int reserved_size_;
volatile int filled_size_;
Buffer cur_buf;
std::vector<Buffer> send_data;
std::vector<PointerData> send_ptr;
};
public:
AsyncAlltoallManager(MPI_Comm comm_, AlltoallBufferHandler* buffer_provider_)
: comm_(comm_)
, buffer_provider_(buffer_provider_)
, scatter_(comm_)
{
CTRACER(AsyncA2A_construtor);
MPI_Comm_size(comm_, &comm_size_);
node_ = new CommTarget[comm_size_]();
d_ = new DynamicDataSet();
pthread_mutex_init(&d_->thread_sync_, NULL);
buffer_size_ = buffer_provider_->buffer_length();
}
virtual ~AsyncAlltoallManager() {
delete [] node_; node_ = NULL;
}
void prepare() {
CTRACER(prepare);
debug("prepare idx=%d", sub_comm);
for(int i = 0; i < comm_size_; ++i) {
node_[i].reserved_size_ = node_[i].filled_size_ = buffer_size_;
}
}
/**
* Asynchronous send.
* When the communicator receive data, it will call fold_received(FoldCommBuffer*) function.
* To reduce the memory consumption, when the communicator detects stacked jobs,
* it also process the tasks in the fiber_man_ except the tasks that have the lowest priority (0).
* This feature realize the fixed memory consumption.
*/
void put(void* ptr, int length, int target)
{
CTRACER(comm_send);
if(length == 0) {
assert(length > 0);
return ;
}
CommTarget& node = node_[target];
//#if ASYNC_COMM_LOCK_FREE
do {
int offset = __sync_fetch_and_add(&node.reserved_size_, length);
if(offset > buffer_size_) {
// wait
while(node.reserved_size_ > buffer_size_) ;
continue ;
}
else if(offset + length > buffer_size_) {
// swap buffer
assert (offset > 0);
while(offset != node.filled_size_) ;
flush(node);
node.cur_buf.ptr = get_send_buffer(); // Maybe, this takes much time.
// This order is important.
offset = node.filled_size_ = 0;
__sync_synchronize(); // membar
node.reserved_size_ = length;
}
buffer_provider_->add(node.cur_buf.ptr, ptr, offset, length);
__sync_fetch_and_add(&node.filled_size_, length);
break;
} while(true);
// #endif
}
void put_ptr(void* ptr, int length, int64_t header, int target) {
CommTarget& node = node_[target];
PointerData data = { ptr, length, header };
pthread_mutex_lock(&node.send_mutex);
node.send_ptr.push_back(data);
pthread_mutex_unlock(&node.send_mutex);
}
void run_with_ptr() {
PROF(profiling::TimeKeeper tk_all);
int es = buffer_provider_->element_size();
int max_size = buffer_provider_->max_size() / (es * comm_size_);
VERVOSE(last_send_size_ = 0);
VERVOSE(last_recv_size_ = 0);
const int MINIMUM_POINTER_SPACE = 40;
for(int loop = 0; ; ++loop) {
USER_START(a2a_merge);
#pragma omp parallel
{
int* counts = scatter_.get_counts();
#pragma omp for schedule(static)
for(int i = 0; i < comm_size_; ++i) {
CommTarget& node = node_[i];
flush(node);
for(int b = 0; b < (int)node.send_data.size(); ++b) {
counts[i] += node.send_data[b].length;
}
for(int b = 0; b < (int)node.send_ptr.size(); ++b) {
PointerData& buffer = node.send_ptr[b];
int length = buffer.length;
if(length == 0) continue;
int size = length + 3;
if(counts[i] + size >= max_size) {
counts[i] = max_size;
break;
}
counts[i] += size;
if(counts[i] + MINIMUM_POINTER_SPACE >= max_size) {
// too small space
break;
}
}
} // #pragma omp for schedule(static)
}
scatter_.sum();
if(loop > 0) {
int has_data = (scatter_.get_send_count() > 0);
MPI_Allreduce(MPI_IN_PLACE, &has_data, 1, MPI_INT, MPI_LOR, comm_);
if(has_data == 0) break;
}
#pragma omp parallel
{
int* offsets = scatter_.get_offsets();
uint8_t* dst = (uint8_t*)buffer_provider_->second_buffer();
#pragma omp for schedule(static)
for(int i = 0; i < comm_size_; ++i) {
CommTarget& node = node_[i];
int& offset = offsets[i];
int count = 0;
for(int b = 0; b < (int)node.send_data.size(); ++b) {
Buffer buffer = node.send_data[b];
void* ptr = buffer.ptr;
int length = buffer.length;
memcpy(dst + offset * es, ptr, length * es);
offset += length;
count += length;
}
for(int b = 0; b < (int)node.send_ptr.size(); ++b) {
PointerData& buffer = node.send_ptr[b];
int64_t* ptr = (int64_t*)buffer.ptr;
int length = buffer.length;
if(length == 0) continue;
int size = length + 3;
if(count + size >= max_size) {
length = max_size - count - 3;
count = max_size;
}
else {
count += size;
}
uint32_t* dst_ptr = (uint32_t*)&dst[offset * es];
dst_ptr[0] = (buffer.header >> 32) | 0x80000000u | 0x40000000u;
dst_ptr[1] = (uint32_t)buffer.header;
dst_ptr[2] = length;
dst_ptr += 3;
for(int i = 0; i < length; ++i) {
dst_ptr[i] = ptr[i] & 0x7FFFFFFF;
}
offset += 3 + length;
buffer.length -= length;
buffer.ptr = (int64_t*)buffer.ptr + length;
if(count + MINIMUM_POINTER_SPACE >= max_size) break;
}
node.send_data.clear();
} // #pragma omp for schedule(static)
} // #pragma omp parallel
USER_END(a2a_merge);
void* sendbuf = buffer_provider_->second_buffer();
void* recvbuf = buffer_provider_->clear_buffers();
MPI_Datatype type = buffer_provider_->data_type();
int recvbufsize = buffer_provider_->max_size();
PROF(merge_time_ += tk_all);
USER_START(a2a_comm);
VERVOSE(if(loop > 0 && mpi.isMaster()) print_with_prefix("Alltoall with pointer (Again)"));
#ifdef PROFILE_REGIONS
timer_start(current_fold);
#endif
scatter_.alltoallv(sendbuf, recvbuf, type, recvbufsize);
#ifdef PROFILE_REGIONS
timer_stop(current_fold);
#endif
PROF(comm_time_ += tk_all);
USER_END(a2a_comm);
VERVOSE(last_send_size_ += scatter_.get_send_count() * es);
VERVOSE(last_recv_size_ += scatter_.get_recv_count() * es);
int* recv_offsets = scatter_.get_recv_offsets();
#pragma omp parallel for
for(int i = 0; i < comm_size_; ++i) {
int offset = recv_offsets[i];
int length = recv_offsets[i+1] - offset;
buffer_provider_->received(recvbuf, offset, length, i);
}
PROF(recv_proc_time_ += tk_all);
buffer_provider_->finish();
PROF(recv_proc_large_time_ += tk_all);
}
// clear
for(int i = 0; i < comm_size_; ++i) {
CommTarget& node = node_[i];
node.send_ptr.clear();
}
}
void run() {
// merge
PROF(profiling::TimeKeeper tk_all);
int es = buffer_provider_->element_size();
VERVOSE(last_send_size_ = 0);
VERVOSE(last_recv_size_ = 0);
USER_START(a2a_merge);
#pragma omp parallel
{
int* counts = scatter_.get_counts();
#pragma omp for schedule(static)
for(int i = 0; i < comm_size_; ++i) {
CommTarget& node = node_[i];
flush(node);
for(int b = 0; b < (int)node.send_data.size(); ++b) {
counts[i] += node.send_data[b].length;
}
} // #pragma omp for schedule(static)
}
scatter_.sum();
#pragma omp parallel
{
int* offsets = scatter_.get_offsets();
uint8_t* dst = (uint8_t*)buffer_provider_->second_buffer();
#pragma omp for schedule(static)
for(int i = 0; i < comm_size_; ++i) {
CommTarget& node = node_[i];
int& offset = offsets[i];
for(int b = 0; b < (int)node.send_data.size(); ++b) {
Buffer buffer = node.send_data[b];
void* ptr = buffer.ptr;
int length = buffer.length;
memcpy(dst + offset * es, ptr, length * es);
offset += length;
}
node.send_data.clear();
} // #pragma omp for schedule(static)
} // #pragma omp parallel
USER_END(a2a_merge);
void* sendbuf = buffer_provider_->second_buffer();
void* recvbuf = buffer_provider_->clear_buffers();
MPI_Datatype type = buffer_provider_->data_type();
int recvbufsize = buffer_provider_->max_size();
PROF(merge_time_ += tk_all);
USER_START(a2a_comm);
#ifdef PROFILE_REGIONS
timer_start(current_fold);
#endif
scatter_.alltoallv(sendbuf, recvbuf, type, recvbufsize);
#ifdef PROFILE_REGIONS
timer_stop(current_fold);
#endif
PROF(comm_time_ += tk_all);
USER_END(a2a_comm);
VERVOSE(last_send_size_ = scatter_.get_send_count() * es);
VERVOSE(last_recv_size_ = scatter_.get_recv_count() * es);
int* recv_offsets = scatter_.get_recv_offsets();
#pragma omp parallel for schedule(dynamic,1)
for(int i = 0; i < comm_size_; ++i) {
int offset = recv_offsets[i];
int length = recv_offsets[i+1] - offset;
buffer_provider_->received(recvbuf, offset, length, i);
}
PROF(recv_proc_time_ += tk_all);
}
#if PROFILING_MODE
void submit_prof_info(int level, bool with_ptr) {
merge_time_.submit("merge a2a data", level);
comm_time_.submit("a2a comm", level);
recv_proc_time_.submit("proc recv data", level);
if(with_ptr) {
recv_proc_large_time_.submit("proc recv large data", level);
}
VERVOSE(profiling::g_pis.submitCounter(last_send_size_, "a2a send data", level);)
VERVOSE(profiling::g_pis.submitCounter(last_recv_size_, "a2a recv data", level);)
}
#endif
#if VERVOSE_MODE
int get_last_send_size() { return last_send_size_; }
#endif
private:
struct DynamicDataSet {
// lock topology
// FoldNode::send_mutex -> thread_sync_
pthread_mutex_t thread_sync_;
} *d_;
MPI_Comm comm_;
int buffer_size_;
int comm_size_;
int node_list_length_;
CommTarget* node_;
AlltoallBufferHandler* buffer_provider_;
ScatterContext scatter_;
PROF(profiling::TimeSpan merge_time_);
PROF(profiling::TimeSpan comm_time_);
PROF(profiling::TimeSpan recv_proc_time_);
PROF(profiling::TimeSpan recv_proc_large_time_);
VERVOSE(int last_send_size_);
VERVOSE(int last_recv_size_);
void flush(CommTarget& node) {
if(node.cur_buf.ptr != NULL) {
node.cur_buf.length = node.filled_size_;
node.send_data.push_back(node.cur_buf);
node.cur_buf.ptr = NULL;
}
}
void* get_send_buffer() {
CTRACER(get_send_buffer);
pthread_mutex_lock(&d_->thread_sync_);
void* ret = buffer_provider_->get_buffer();
pthread_mutex_unlock(&d_->thread_sync_);
return ret;
}
};
// Allgather
class MpiCompletionHandler {
public:
virtual ~MpiCompletionHandler() { }
virtual void complete(MPI_Status* status) = 0;
};
class MpiRequestManager {
public:
MpiRequestManager(int MAX_REQUESTS)
: MAX_REQUESTS(MAX_REQUESTS)
, finish_count(0)
, reqs(new MPI_Request[MAX_REQUESTS])
, handlers(new MpiCompletionHandler*[MAX_REQUESTS])
{
for(int i = 0; i < MAX_REQUESTS; ++i) {
reqs[i] = MPI_REQUEST_NULL;
empty_list.push_back(i);
}
}
~MpiRequestManager() {
delete [] reqs; reqs = NULL;
delete [] handlers; handlers = NULL;
}
MPI_Request* submit_handler(MpiCompletionHandler* handler) {
if(empty_list.size() == 0) {
fprintf(IMD_OUT, "No more empty MPI requests...\n");
throw "No more empty MPI requests...";
}
int empty = empty_list.back();
empty_list.pop_back();
handlers[empty] = handler;
return &reqs[empty];
}
void finished() {
--finish_count;
}
void run(int finish_count__) {
finish_count += finish_count__;
while(finish_count > 0) {
if(empty_list.size() == MAX_REQUESTS) {
fprintf(IMD_OUT, "Error: No active request\n");
throw "Error: No active request";
}
int index;
MPI_Status status;
MPI_Waitany(MAX_REQUESTS, reqs, &index, &status);
if(index == MPI_UNDEFINED) {
fprintf(IMD_OUT, "MPI_Waitany returns MPI_UNDEFINED ...\n");
throw "MPI_Waitany returns MPI_UNDEFINED ...";
}
MpiCompletionHandler* handler = handlers[index];
reqs[index] = MPI_REQUEST_NULL;
empty_list.push_back(index);
handler->complete(&status);
}
}
private:
int MAX_REQUESTS;
int finish_count;
MPI_Request *reqs;
MpiCompletionHandler** handlers;
std::vector<int> empty_list;
};
template <typename T>
class AllgatherHandler : public MpiCompletionHandler {
public:
AllgatherHandler() { }
virtual ~AllgatherHandler() { }
void start(MpiRequestManager* req_man_, T *buffer_, int* count_, int* offset_, MPI_Comm comm_,
int rank_, int size_, int left_, int right_, int tag_)
{
req_man = req_man_;
buffer = buffer_;
count = count_;
offset = offset_;
comm = comm_;
rank = rank_;
size = size_;
left = left_;
right = right_;
tag = tag_;
current = 1;
l_sendidx = rank;
l_recvidx = (rank + size + 1) % size;
r_sendidx = rank;
r_recvidx = (rank + size - 1) % size;
next();
}
virtual void complete(MPI_Status* status) {
if(++complete_count == 4) {
next();
}
}
private:
MpiRequestManager* req_man;
T *buffer;
int *count;
int *offset;
MPI_Comm comm;
int rank;
int size;
int left;
int right;
int tag;
int current;
int l_sendidx;
int l_recvidx;
int r_sendidx;
int r_recvidx;
int complete_count;
void next() {
if(current >= size) {
req_man->finished();
return ;
}
if(l_sendidx >= size) l_sendidx -= size;
if(l_recvidx >= size) l_recvidx -= size;
if(r_sendidx < 0) r_sendidx += size;
if(r_recvidx < 0) r_recvidx += size;
int l_send_off = offset[l_sendidx];
int l_send_cnt = count[l_sendidx] / 2;
int l_recv_off = offset[l_recvidx];
int l_recv_cnt = count[l_recvidx] / 2;
int r_send_off = offset[r_sendidx] + count[r_sendidx] / 2;
int r_send_cnt = count[r_sendidx] - count[r_sendidx] / 2;
int r_recv_off = offset[r_recvidx] + count[r_recvidx] / 2;
int r_recv_cnt = count[r_recvidx] - count[r_recvidx] / 2;
MPI_Irecv(&buffer[l_recv_off], l_recv_cnt, MpiTypeOf<T>::type,
right, tag, comm, req_man->submit_handler(this));
MPI_Irecv(&buffer[r_recv_off], r_recv_cnt, MpiTypeOf<T>::type,
left, tag, comm, req_man->submit_handler(this));
MPI_Isend(&buffer[l_send_off], l_send_cnt, MpiTypeOf<T>::type,
left, tag, comm, req_man->submit_handler(this));
MPI_Isend(&buffer[r_send_off], r_send_cnt, MpiTypeOf<T>::type,
right, tag, comm, req_man->submit_handler(this));
++current;
++l_sendidx;
++l_recvidx;
--r_sendidx;
--r_recvidx;
complete_count = 0;
}
};
template <typename T>
class AllgatherStep1Handler : public MpiCompletionHandler {
public:
AllgatherStep1Handler() { }
virtual ~AllgatherStep1Handler() { }
void start(MpiRequestManager* req_man_, T *buffer_, int* count_, int* offset_,
COMM_2D comm_, int unit_x_, int unit_y_, int steps_, int tag_)
{
req_man = req_man_;
buffer = buffer_;
count = count_;
offset = offset_;
comm = comm_;
unit_x = unit_x_;
unit_y = unit_y_;
steps = steps_;
tag = tag_;
current = 1;
send_to = get_rank(-1);
recv_from = get_rank(1);
next();
}
virtual void complete(MPI_Status* status) {
if(++complete_count == 2) {
next();
}
}
private:
MpiRequestManager* req_man;
T *buffer;
int *count;
int *offset;
COMM_2D comm;
int unit_x;
int unit_y;
int steps;
int tag;
int send_to;
int recv_from;
int current;
int complete_count;
int get_rank(int diff) {
int pos_x = (comm.rank_x + unit_x * diff + comm.size_x) % comm.size_x;
int pos_y = (comm.rank_y + unit_y * diff + comm.size_y) % comm.size_y;
return comm.rank_map[pos_x + pos_y * comm.size_x];
}
void next() {
if(current >= steps) {
req_man->finished();
return ;
}
int sendidx = get_rank(current - 1);
int recvidx = get_rank(current);
int send_off = offset[sendidx];
int send_cnt = count[sendidx];
int recv_off = offset[recvidx];
int recv_cnt = count[recvidx];
MPI_Irecv(&buffer[recv_off], recv_cnt, MpiTypeOf<T>::type,
recv_from, tag, comm.comm, req_man->submit_handler(this));
MPI_Isend(&buffer[send_off], send_cnt, MpiTypeOf<T>::type,
send_to, tag, comm.comm, req_man->submit_handler(this));
++current;
complete_count = 0;
}
};
template <typename T>
class AllgatherStep2Handler : public MpiCompletionHandler {
public:
AllgatherStep2Handler() { }
virtual ~AllgatherStep2Handler() { }
void start(MpiRequestManager* req_man_, T *buffer_, int* count_, int* offset_,
COMM_2D comm_, int unit_x_, int unit_y_, int steps_, int width_, int tag_)
{
req_man = req_man_;
buffer = buffer_;
count = count_;
offset = offset_;
comm = comm_;
unit_x = unit_x_;
unit_y = unit_y_;
steps = steps_;
width = width_;
tag = tag_;
current = 1;
send_to = get_rank(-1, 0);
recv_from = get_rank(1, 0);
next();
}
virtual void complete(MPI_Status* status) {
if(++complete_count == width*2) {
next();
}
}
private:
MpiRequestManager* req_man;
T *buffer;
int *count;
int *offset;
COMM_2D comm;
int unit_x;
int unit_y;
int steps;
int width;
int tag;
int send_to;
int recv_from;
int current;
int complete_count;
int get_rank(int step_diff, int idx) {
int pos_x = (comm.rank_x + unit_x * step_diff + (!unit_x * idx) + comm.size_x) % comm.size_x;
int pos_y = (comm.rank_y + unit_y * step_diff + (!unit_y * idx) + comm.size_y) % comm.size_y;
return comm.rank_map[pos_x + pos_y * comm.size_x];
}
void next() {
if(current >= steps) {
req_man->finished();
return ;
}
for(int i = 0; i < width; ++i) {
int sendidx = get_rank(current - 1, i);
int recvidx = get_rank(current, i);
int send_off = offset[sendidx];
int send_cnt = count[sendidx];
int recv_off = offset[recvidx];
int recv_cnt = count[recvidx];
MPI_Irecv(&buffer[recv_off], recv_cnt, MpiTypeOf<T>::type,
recv_from, tag, comm.comm, req_man->submit_handler(this));
MPI_Isend(&buffer[send_off], send_cnt, MpiTypeOf<T>::type,
send_to, tag, comm.comm, req_man->submit_handler(this));
}
++current;
complete_count = 0;
}
};
template <typename T>
void my_allgatherv_2d(T *sendbuf, int send_count, T *recvbuf, int* recv_count, int* recv_offset, COMM_2D comm)
{
// copy own data
memcpy(&recvbuf[recv_offset[comm.rank]], sendbuf, sizeof(T) * send_count);
if(mpi.isMultiDimAvailable == false) {
MpiRequestManager req_man(8);
AllgatherHandler<T> handler;
int size; MPI_Comm_size(comm.comm, &size);
int rank; MPI_Comm_rank(comm.comm, &rank);
int left = (rank + size - 1) % size;
int right = (rank + size + 1) % size;
handler.start(&req_man, recvbuf, recv_count, recv_offset, comm.comm,
rank, size, left, right, PRM::MY_EXPAND_TAG1);
req_man.run(1);
return ;
}
//MPI_Allgatherv(sendbuf, send_count, MpiTypeOf<T>::type, recvbuf, recv_count, recv_offset, MpiTypeOf<T>::type, comm.comm);
//return;
MpiRequestManager req_man((comm.size_x + comm.size_y)*4);
int split_count[4][comm.size];
int split_offset[4][comm.size];
for(int s = 0; s < 4; ++s) {
for(int i = 0; i < comm.size; ++i) {
int max = recv_count[i];
int split = (max + 3) / 4;
int start = recv_offset[i] + std::min(max, split * s);
int end = recv_offset[i] + std::min(max, split * (s+1));
split_count[s][i] = end - start;
split_offset[s][i] = start;
}
}
{
AllgatherStep1Handler<T> handler[4];
handler[0].start(&req_man, recvbuf, split_count[0], split_offset[0], comm, 1, 0, comm.size_x, PRM::MY_EXPAND_TAG1);
handler[1].start(&req_man, recvbuf, split_count[1], split_offset[1], comm,-1, 0, comm.size_x, PRM::MY_EXPAND_TAG1);
handler[2].start(&req_man, recvbuf, split_count[2], split_offset[2], comm, 0, 1, comm.size_y, PRM::MY_EXPAND_TAG2);
handler[3].start(&req_man, recvbuf, split_count[3], split_offset[3], comm, 0,-1, comm.size_y, PRM::MY_EXPAND_TAG2);
req_man.run(4);
}
{
AllgatherStep2Handler<T> handler[4];
handler[0].start(&req_man, recvbuf, split_count[0], split_offset[0], comm, 0, 1, comm.size_y, comm.size_x, PRM::MY_EXPAND_TAG1);
handler[1].start(&req_man, recvbuf, split_count[1], split_offset[1], comm, 0,-1, comm.size_y, comm.size_x, PRM::MY_EXPAND_TAG1);
handler[2].start(&req_man, recvbuf, split_count[2], split_offset[2], comm, 1, 0, comm.size_x, comm.size_y, PRM::MY_EXPAND_TAG2);
handler[3].start(&req_man, recvbuf, split_count[3], split_offset[3], comm,-1, 0, comm.size_x, comm.size_y, PRM::MY_EXPAND_TAG2);
req_man.run(4);
}
}
template <typename T>
void my_allgather_2d(T *sendbuf, int count, T *recvbuf, COMM_2D comm)
{
memcpy(&recvbuf[count * comm.rank], sendbuf, sizeof(T) * count);
int recv_count[comm.size];
int recv_offset[comm.size+1];
recv_offset[0] = 0;
for(int i = 0; i < comm.size; ++i) {
recv_count[i] = count;
recv_offset[i+1] = recv_offset[i] + count;
}
my_allgatherv_2d(sendbuf, count, recvbuf, recv_count, recv_offset, comm);
}
#undef debug
#endif /* ABSTRACT_COMM_HPP_ */
| 21,541 | 9,579 |
/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
http://www.etlcpp.com
Copyright(c) 2014 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "UnitTest++/UnitTest++.h"
#include "ExtraCheckMacros.h"
#include "data.h"
#include <set>
#include <vector>
#include <string>
#include "etl/pool.h"
#include "etl/largest.h"
#if defined(ETL_COMPILER_GCC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
typedef TestDataDC<std::string> Test_Data;
typedef TestDataNDC<std::string> Test_Data2;
namespace
{
struct D0
{
D0()
{
}
};
struct D1
{
D1(const std::string& a_)
: a(a_)
{
}
std::string a;
};
struct D2
{
D2(const std::string& a_, const std::string& b_)
: a(a_),
b(b_)
{
}
std::string a;
std::string b;
};
struct D3
{
D3(const std::string& a_, const std::string& b_, const std::string& c_)
: a(a_),
b(b_),
c(c_)
{
}
std::string a;
std::string b;
std::string c;
};
struct D4
{
D4(const std::string& a_, const std::string& b_, const std::string& c_, const std::string& d_)
: a(a_),
b(b_),
c(c_),
d(d_)
{
}
std::string a;
std::string b;
std::string c;
std::string d;
};
bool operator == (const D0&, const D0&)
{
return true;
}
bool operator == (const D1& lhs, const D1& rhs)
{
return (lhs.a == rhs.a);
}
bool operator == (const D2& lhs, const D2& rhs)
{
return (lhs.a == rhs.a) && (lhs.b == rhs.b);
}
bool operator == (const D3& lhs, const D3& rhs)
{
return (lhs.a == rhs.a) && (lhs.b == rhs.b) && (lhs.c == rhs.c);
}
bool operator == (const D4& lhs, const D4& rhs)
{
return (lhs.a == rhs.a) && (lhs.b == rhs.b) && (lhs.c == rhs.c) && (lhs.d == rhs.d);
}
std::ostream& operator <<(std::ostream& os, const D0&)
{
return os;
}
std::ostream& operator <<(std::ostream& os, const D1& d)
{
os << d.a;
return os;
}
std::ostream& operator <<(std::ostream& os, const D2& d)
{
os << d.a << " " << d.b;
return os;
}
std::ostream& operator <<(std::ostream& os, const D3& d)
{
os << d.a << " " << d.b << " " << d.c;
return os;
}
std::ostream& operator <<(std::ostream& os, const D4& d)
{
os << d.a << " " << d.b << " " << d.c << " " << d.d;
return os;
}
SUITE(test_pool)
{
//*************************************************************************
TEST(test_allocate)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1 = nullptr;
Test_Data* p2 = nullptr;
Test_Data* p3 = nullptr;
Test_Data* p4 = nullptr;
CHECK_NO_THROW(p1 = pool.allocate<Test_Data>());
CHECK_NO_THROW(p2 = pool.allocate<Test_Data>());
CHECK_NO_THROW(p3 = pool.allocate<Test_Data>());
CHECK_NO_THROW(p4 = pool.allocate<Test_Data>());
CHECK(p1 != p2);
CHECK(p1 != p3);
CHECK(p1 != p4);
CHECK(p2 != p3);
CHECK(p2 != p4);
CHECK(p3 != p4);
CHECK_THROW(pool.allocate<Test_Data>(), etl::pool_no_allocation);
}
//*************************************************************************
TEST(test_release)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1 = pool.allocate<Test_Data>();
Test_Data* p2 = pool.allocate<Test_Data>();
Test_Data* p3 = pool.allocate<Test_Data>();
Test_Data* p4 = pool.allocate<Test_Data>();
CHECK_NO_THROW(pool.release(p2));
CHECK_NO_THROW(pool.release(p3));
CHECK_NO_THROW(pool.release(p1));
CHECK_NO_THROW(pool.release(p4));
CHECK_EQUAL(4U, pool.available());
Test_Data not_in_pool;
CHECK_THROW(pool.release(¬_in_pool), etl::pool_object_not_in_pool);
}
//*************************************************************************
TEST(test_allocate_release)
{
etl::pool<Test_Data, 4> pool;
Test_Data* p1 = pool.allocate<Test_Data>();
Test_Data* p2 = pool.allocate<Test_Data>();
Test_Data* p3 = pool.allocate<Test_Data>();
Test_Data* p4 = pool.allocate<Test_Data>();
// Allocated p1, p2, p3, p4
CHECK_EQUAL(0U, pool.available());
CHECK_NO_THROW(pool.release(p2));
CHECK_NO_THROW(pool.release(p3));
// Allocated p1, p4
CHECK_EQUAL(2U, pool.available());
Test_Data* p5 = pool.allocate<Test_Data>();
Test_Data* p6 = pool.allocate<Test_Data>();
// Allocated p1, p4, p5, p6
CHECK_EQUAL(0U, pool.available());
CHECK(p5 != p1);
CHECK(p5 != p4);
CHECK(p6 != p1);
CHECK(p6 != p4);
CHECK_NO_THROW(pool.release(p5));
// Allocated p1, p4, p6
CHECK_EQUAL(1U, pool.available());
Test_Data* p7 = pool.allocate<Test_Data>();
// Allocated p1, p4, p6, p7
CHECK(p7 != p1);
CHECK(p7 != p4);
CHECK(p7 != p6);
CHECK(pool.full());
}
//*************************************************************************
TEST(test_available)
{
etl::pool<Test_Data, 4> pool;
CHECK_EQUAL(4U, pool.available());
Test_Data* p;
p = pool.allocate<Test_Data>();
CHECK_EQUAL(3U, pool.available());
p = pool.allocate<Test_Data>();
CHECK_EQUAL(2U, pool.available());
p = pool.allocate<Test_Data>();
CHECK_EQUAL(1U, pool.available());
p = pool.allocate<Test_Data>();
CHECK_EQUAL(0U, pool.available());
}
//*************************************************************************
TEST(test_max_size)
{
etl::pool<Test_Data, 4> pool;
CHECK(pool.max_size() == 4U);
}
//*************************************************************************
TEST(test_size)
{
etl::pool<Test_Data, 4> pool;
CHECK_EQUAL(0U, pool.size());
Test_Data* p;
p = pool.allocate<Test_Data>();
CHECK_EQUAL(1U, pool.size());
p = pool.allocate<Test_Data>();
CHECK_EQUAL(2U, pool.size());
p = pool.allocate<Test_Data>();
CHECK_EQUAL(3U, pool.size());
p = pool.allocate<Test_Data>();
CHECK_EQUAL(4U, pool.size());
}
//*************************************************************************
TEST(test_empty_full)
{
etl::pool<Test_Data, 4> pool;
CHECK(pool.empty());
CHECK(!pool.full());
Test_Data* p;
p = pool.allocate<Test_Data>();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate<Test_Data>();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate<Test_Data>();
CHECK(!pool.empty());
CHECK(!pool.full());
p = pool.allocate<Test_Data>();
CHECK(!pool.empty());
CHECK(pool.full());
}
//*************************************************************************
TEST(test_is_in_pool)
{
etl::pool<Test_Data, 4> pool;
Test_Data not_in_pool;
Test_Data* p1 = pool.allocate<Test_Data>();
CHECK(pool.is_in_pool(p1));
CHECK(!pool.is_in_pool(¬_in_pool));
}
//*************************************************************************
TEST(test_generic_storage)
{
union Storage
{
uint64_t dummy; // For alignment purposes.
char buffer[1000];
};
etl::pool<Storage, 4> pool;
Test_Data* pdata = pool.allocate<Test_Data>();
new (pdata) Test_Data("ABC", 3);
etl::array<int, 10>* parray = pool.allocate<etl::array<int, 10>>();
new (parray) etl::array<int, 10>();
parray->fill(0x12345678);
etl::array<int, 10> compare;
compare.fill(0x12345678);
CHECK(pdata->value == "ABC");
CHECK(pdata->index == 3);
CHECK(*parray == compare);
pool.release(parray);
pool.release(pdata);
CHECK_EQUAL(4U, pool.available());
}
//*************************************************************************
TEST(test_type_error)
{
struct Test
{
uint64_t a;
uint64_t b;
};
etl::pool<uint32_t, 4> pool;
etl::ipool& ip = pool;
CHECK_THROW(ip.allocate<Test>(), etl::pool_element_size);
}
//*************************************************************************
TEST(test_generic_allocate)
{
typedef etl::largest<uint8_t, uint32_t, double, Test_Data> largest;
etl::generic_pool<largest::size, largest::alignment, 4> pool;
uint8_t* p1 = nullptr;
uint32_t* p2 = nullptr;
double* p3 = nullptr;
Test_Data* p4 = nullptr;
CHECK_NO_THROW(p1 = pool.allocate<uint8_t>());
CHECK_NO_THROW(p2 = pool.allocate<uint32_t>());
CHECK_NO_THROW(p3 = pool.allocate<double>());
CHECK_NO_THROW(p4 = pool.allocate<Test_Data>());
}
};
//*************************************************************************
TEST(test_create_destroy)
{
etl::pool<D0, 4> pool0;
etl::pool<D1, 4> pool1;
etl::pool<D2, 4> pool2;
etl::pool<D3, 4> pool3;
etl::pool<D4, 4> pool4;
D0* p0 = pool0.create<D0>();
D1* p1 = pool1.create<D1>("1");
D2* p2 = pool2.create<D2>("1", "2");
D3* p3 = pool3.create<D3>("1", "2", "3");
D4* p4 = pool4.create<D4>("1", "2", "3", "4");
CHECK_EQUAL(pool0.max_size() - 1, pool0.available());
CHECK_EQUAL(1U, pool0.size());
CHECK_EQUAL(pool1.max_size() - 1, pool1.available());
CHECK_EQUAL(1U, pool1.size());
CHECK_EQUAL(pool2.max_size() - 1, pool2.available());
CHECK_EQUAL(1U, pool2.size());
CHECK_EQUAL(pool3.max_size() - 1, pool3.available());
CHECK_EQUAL(1U, pool3.size());
CHECK_EQUAL(pool4.max_size() - 1, pool4.available());
CHECK_EQUAL(1U, pool4.size());
CHECK_EQUAL(D0(), *p0);
CHECK_EQUAL(D1("1"), *p1);
CHECK_EQUAL(D2("1", "2"), *p2);
CHECK_EQUAL(D3("1", "2", "3"), *p3);
CHECK_EQUAL(D4("1", "2", "3", "4"), *p4);
pool0.destroy<D0>(p0);
pool1.destroy<D1>(p1);
pool2.destroy<D2>(p2);
pool3.destroy<D3>(p3);
pool4.destroy<D4>(p4);
CHECK_EQUAL(pool0.max_size(), pool0.available());
CHECK_EQUAL(0U, pool0.size());
CHECK_EQUAL(pool1.max_size(), pool1.available());
CHECK_EQUAL(0U, pool1.size());
CHECK_EQUAL(pool2.max_size(), pool2.available());
CHECK_EQUAL(0U, pool2.size());
CHECK_EQUAL(pool3.max_size(), pool3.available());
CHECK_EQUAL(0U, pool3.size());
CHECK_EQUAL(pool4.max_size(), pool4.available());
CHECK_EQUAL(0U, pool4.size());
}
}
#if defined(ETL_COMPILER_GCC)
#pragma GCC diagnostic pop
#endif
| 11,797 | 4,495 |
#pragma once
#include "vfunc.hpp"
#include "../utilities/utilities.hpp"
#include "../utilities/math.hpp"
#include "../utilities/netvars.hpp"
#define NETVAR(type, name, table, netvar) \
type& name##() const { \
static const auto _##name = Netvars::GetOffset(hash::fnv1a_32(table), hash::fnv1a_32(netvar)); \
return *(type*)(uintptr_t(this) + _##name); \
}
class CWeapon;
class CEntity {
public:
int GetFlags();
size_t GetIndex();
NETVAR(uintptr_t, m_hActiveWeapon, "DT_BaseCombatCharacter", "m_hActiveWeapon");
NETVAR(uintptr_t, m_vecOrigin, "DT_BaseEntity", "m_vecOrigin");
CWeapon* GetActiveWeapon();
const char* GetClassName();
bool IsNPC();
bool IsPlayer();
bool IsDormant();
bool IsAlive();
int GetHealth();
int GetMaxHealth();
Vector GetViewOffset();
Vector GetEyePos();
Vector& GetAbsOrigin();
bool SetupBones(matrix3x4_t* pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime);
void* GetModel();
int& GetTickBase();
};
class CWeapon {
public:
bool UsesLua();
bool PushEntity();
bool HasPrimaryAmmo();
float LUASpread();
const char* GetWeaponBase();
float TTTSpread();
float LUASpread2();
const Vector& orgGetBulletSpread();
Vector GetBulletSpread();
const char* GetName();
bool IsExplosive();
bool IsHoldingTool();
bool IsNospreadWeapon();
float m_flNextPrimaryAttack();
bool CanFire();
};
| 1,353 | 537 |
#ifndef QT_RESOURCE_SYSTEM_HPP
#define QT_RESOURCE_SYSTEM_HPP
#include "core_dependency_system/i_interface.hpp"
#include "core_serialization/i_resource_system.hpp"
namespace wgt
{
class QtResourceSystem : public Implements<IResourceSystem>
{
public:
QtResourceSystem();
virtual ~QtResourceSystem();
virtual bool exists(const char* resource) const override;
virtual BinaryBlockPtr readBinaryContent(const char* resource) const override;
};
} // end namespace wgt
#endif
| 476 | 154 |
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Common.hpp"
namespace s3d
{
/// @brief 入力デバイスの種類
enum class InputDeviceType : uint8
{
/// @brief 未定義
Undefined,
/// @brief キーボード
Keyboard,
/// @brief マウス
Mouse,
/// @brief ゲームパッド
Gamepad,
/// @brief XInput 対応ゲームコントローラー
XInput,
};
}
| 560 | 265 |
#include <iostream>
#include <string>
using namespace std;
string DigitToWord(int digitIn) {
// FINISH
}
string TensDigitToWord(int digitIn) {
// FINISH
}
string TwoDigitNumToWords(int numIn) {
// FINISH
}
int main() {
// FINISH
return 0;
} | 269 | 119 |
#include <iostream>
#include <opencv2/opencv.hpp>
#include <fstream>
using namespace cv;
/**
* @brief Checks whether the pixel is part of Peak/ is Peak, We are looking for 8-conn points
*
* @param mxz
* @param conn_points
* @return true
* @return false
*/
bool isPeak(cv::Mat mx[], std::vector<cv::Point>& conn_points){
cv::Point poi_point = conn_points.back();
int row = poi_point.y;
int col = poi_point.x;
float poi_val = mx[0].at<float>(poi_point);
bool isPeakEle = true;
for(int mask_row = row - 1; mask_row <= row + 1 ; mask_row++){
for(int mask_col = col - 1; mask_col <= col + 1 ; mask_col++){
if(mask_row == row && mask_col == col){
continue;
}
float conn_pt_val = mx[0].at<float>(mask_row, mask_col);
if(poi_val < conn_pt_val){
isPeakEle = false;
break;
}
if(poi_val == conn_pt_val){
int Peak_status = mx[1].at<uchar>(mask_row, mask_col);
if(Peak_status == 0){
isPeakEle = false;
break;
}
else if(Peak_status == 1){
isPeakEle = true;
break;
}
else{
cv::Point p(mask_col, mask_row);
std::vector<cv::Point>::iterator it;
it = std::find (conn_points.begin(), conn_points.end(), p);
if(it == conn_points.end()){
conn_points.push_back(p);
isPeakEle = isPeakEle && isPeak(mx, conn_points);
}
}
}
}
if(isPeakEle == false){
break;
}
}
return isPeakEle;
}
/**
* @brief This is equivalent to imregionalmax(img, conn = 8) of Matlab
* It takes floating point matrix, finds all local maximas and put them in 8UC1 matrix
* pls refer: https://in.mathworks.com/help/images/ref/imregionalmax.html for imregionalmax
* eg: I/P
* 10 10 10 10 10 10 10 10 10 10
10 22 22 22 10 10 44 10 10 10
10 22 22 22 10 10 10 45 10 10
10 22 22 22 10 10 10 10 44 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 33 33 33 10 10
10 10 10 10 10 33 33 33 10 10
10 10 10 10 10 33 33 33 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
* O/P
0 0 0 0 0 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0
0 1 1 1 0 0 0 1 0 0
0 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
* @param src
* @param conn
* @return cv::Mat
*/
cv::Mat imregionalmax(cv::Mat& src){
cv::Mat padded;
cv::copyMakeBorder(src, padded, 1, 1, 1, 1, BORDER_CONSTANT, Scalar::all(-1));
Mat mx_ch1(padded.rows, padded.cols, CV_8UC1, Scalar(2)); //Peak elements will be represented by 1, others by 0, initializing Mat with 2 for differentiation
cv::Mat mx[2] = {padded, mx_ch1}; //mx[0] is padded image, mx[1] is regional maxima matrix
int mx_rows = mx[0].rows;
int mx_cols = mx[0].cols;
cv::Mat dest(mx[0].size(), CV_8UC1);
//Check each pixel for local max
for(int row = 1; row < mx_rows - 1 ; row++){
for(int col = 1; col < mx_cols - 1 ; col++){
std::vector<cv::Point> conn_points; //this vector holds all connected points for candidate pixel
cv::Point p(col, row);
conn_points.push_back(p);
bool isPartOfPeak = isPeak(mx, conn_points);
if(isPartOfPeak){
mx[1].at<uchar>(row, col) = 1;
}
else{
mx[1].at<uchar>(row, col) = 0;
}
}
}
dest = mx[1](cv::Rect(1, 1,src.cols, src.rows));
return dest;
}
int main(){
Mat src = (Mat_<float>(10, 10) << 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 22, 22, 22, 10, 10, 44, 10, 10, 10,
10, 22, 22, 22, 10, 10, 10, 45, 10, 10,
10, 22, 22, 22, 10, 10, 10, 10, 44, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 33, 33, 33, 10, 10,
10, 10, 10, 10, 10, 33, 33, 33, 10, 10,
10, 10, 10, 10, 10, 33, 33, 33, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10
);
cv::Mat peaks = imregionalmax(src);
for(int row = 0 ; row < peaks.rows ; row++) {
for(int col = 0 ; col < peaks.cols ; col++) {
std::cout << (int)peaks.at<uchar>(row, col)<< ", ";
}
std::cout<<std::endl;
}
} | 5,496 | 2,208 |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb
Copyright (C) 2004 Mike Parker
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file g2.hpp
\brief Two-factor additive Gaussian Model G2++
*/
#ifndef quantlib_two_factor_models_g2_h
#define quantlib_two_factor_models_g2_h
#include <ql/models/shortrate/twofactormodel.hpp>
#include <ql/processes/ornsteinuhlenbeckprocess.hpp>
#include <ql/instruments/swaption.hpp>
namespace QuantLib {
//! Two-additive-factor gaussian model class.
/*! This class implements a two-additive-factor model defined by
\f[
dr_t = \varphi(t) + x_t + y_t
\f]
where \f$ x_t \f$ and \f$ y_t \f$ are defined by
\f[
dx_t = -a x_t dt + \sigma dW^1_t, x_0 = 0
\f]
\f[
dy_t = -b y_t dt + \sigma dW^2_t, y_0 = 0
\f]
and \f$ dW^1_t dW^2_t = \rho dt \f$.
\bug This class was not tested enough to guarantee
its functionality.
\ingroup shortrate
*/
class G2 : public TwoFactorModel,
public AffineModel,
public TermStructureConsistentModel {
public:
G2(const Handle<YieldTermStructure>& termStructure,
Real a = 0.1,
Real sigma = 0.01,
Real b = 0.1,
Real eta = 0.01,
Real rho = -0.75);
ext::shared_ptr<ShortRateDynamics> dynamics() const override;
Real discountBond(Time now, Time maturity, Array factors) const override {
QL_REQUIRE(factors.size()>1,
"g2 model needs two factors to compute discount bond");
return discountBond(now, maturity, factors[0], factors[1]);
}
Real discountBond(Time, Time, Rate, Rate) const;
Real discountBondOption(Option::Type type,
Real strike,
Time maturity,
Time bondMaturity) const override;
Real swaption(const Swaption::arguments& arguments,
Rate fixedRate,
Real range,
Size intervals) const;
DiscountFactor discount(Time t) const override { return termStructure()->discount(t); }
Real a() const { return a_(0.0); }
Real sigma() const { return sigma_(0.0); }
Real b() const { return b_(0.0); }
Real eta() const { return eta_(0.0); }
Real rho() const { return rho_(0.0); }
protected:
void generateArguments() override;
Real A(Time t, Time T) const;
Real B(Real x, Time t) const;
private:
class Dynamics;
class FittingParameter;
Real sigmaP(Time t, Time s) const;
Parameter& a_;
Parameter& sigma_;
Parameter& b_;
Parameter& eta_;
Parameter& rho_;
Parameter phi_;
Real V(Time t) const;
class SwaptionPricingFunction;
friend class SwaptionPricingFunction;
};
class G2::Dynamics : public TwoFactorModel::ShortRateDynamics {
public:
Dynamics(const Parameter& fitting,
Real a,
Real sigma,
Real b,
Real eta,
Real rho)
: ShortRateDynamics(ext::shared_ptr<StochasticProcess1D>(
new OrnsteinUhlenbeckProcess(a, sigma)),
ext::shared_ptr<StochasticProcess1D>(
new OrnsteinUhlenbeckProcess(b, eta)),
rho),
fitting_(fitting) {}
Rate shortRate(Time t, Real x, Real y) const override { return fitting_(t) + x + y; }
private:
Parameter fitting_;
};
//! Analytical term-structure fitting parameter \f$ \varphi(t) \f$.
/*! \f$ \varphi(t) \f$ is analytically defined by
\f[
\varphi(t) = f(t) +
\frac{1}{2}(\frac{\sigma(1-e^{-at})}{a})^2 +
\frac{1}{2}(\frac{\eta(1-e^{-bt})}{b})^2 +
\rho\frac{\sigma(1-e^{-at})}{a}\frac{\eta(1-e^{-bt})}{b},
\f]
where \f$ f(t) \f$ is the instantaneous forward rate at \f$ t \f$.
*/
class G2::FittingParameter : public TermStructureFittingParameter {
private:
class Impl : public Parameter::Impl {
public:
Impl(const Handle<YieldTermStructure>& termStructure,
Real a,
Real sigma,
Real b,
Real eta,
Real rho)
: termStructure_(termStructure),
a_(a), sigma_(sigma), b_(b), eta_(eta), rho_(rho) {}
Real value(const Array&, Time t) const override {
Rate forward = termStructure_->forwardRate(t, t,
Continuous,
NoFrequency);
Real temp1 = sigma_*(1.0-std::exp(-a_*t))/a_;
Real temp2 = eta_*(1.0-std::exp(-b_*t))/b_;
Real value = 0.5*temp1*temp1 + 0.5*temp2*temp2 +
rho_*temp1*temp2 + forward;
return value;
}
private:
Handle<YieldTermStructure> termStructure_;
Real a_, sigma_, b_, eta_, rho_;
};
public:
FittingParameter(const Handle<YieldTermStructure>& termStructure,
Real a,
Real sigma,
Real b,
Real eta,
Real rho)
: TermStructureFittingParameter(ext::shared_ptr<Parameter::Impl>(
new FittingParameter::Impl(termStructure, a, sigma,
b, eta, rho))) {}
};
}
#endif
| 6,599 | 1,991 |
#pragma once
#include <memory>
#include "factory.hpp"
namespace blackhole {
inline namespace v1 {
namespace config {
class json_t;
template<>
class factory_traits<json_t> {
public:
/// Constructs and initializes the JSON config factory by reading the given stream reference
/// until EOF and parsing its content.
///
/// The content should be valid JSON object.
///
/// \param stream lvalue reference to the input stream.
static auto construct(std::istream& stream) -> std::unique_ptr<factory_t>;
/// Constructs and initializes the JSON config factory by reading the given stream until EOF
/// and parsing its content.
///
/// The content should be valid JSON object.
///
/// \overload
/// \param stream rvalue reference to the input stream.
static auto construct(std::istream&& stream) -> std::unique_ptr<factory_t>;
};
} // namespace config
} // namespace v1
} // namespace blackhole
| 957 | 263 |
// Problem Link:
// https://leetcode.com/problems/diameter-of-binary-tree/
// Approach 1
// TC: O(n^2)
// SC: O(n)
// Approach 2
// TC: O(n)
// SC: O(n)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define deb(x) cout << #x << ": " << x << "\n"
class TreeNode
{
public:
TreeNode *left;
int val;
TreeNode *right;
TreeNode() { TreeNode(-1); }
TreeNode(int _val) : left(NULL), val(_val), right(NULL) {}
};
// Approach 1
int maxHeight(TreeNode *root)
{
if (!root)
return 0;
return max(maxHeight(root->left) + 1, maxHeight(root->right) + 1);
}
int diameterOfBinaryTree1(TreeNode *root)
{
if (!root)
return 0;
int currMax = maxHeight(root->left) + maxHeight(root->right);
currMax = max(diameterOfBinaryTree1(root->left), currMax);
currMax = max(diameterOfBinaryTree1(root->right), currMax);
return currMax;
}
// Approach 2
int helper(TreeNode *root, int &res)
{
if (!root)
return 0;
int leftDia = helper(root->left, res);
int rightDia = helper(root->right, res);
res = max(res, leftDia + rightDia);
return max(leftDia + 1, rightDia + 1);
}
int diameterOfBinaryTree2(TreeNode *root)
{
int res{};
helper(root, res);
return res;
}
void solve()
{
TreeNode *root = new TreeNode(10);
root->left = new TreeNode(20);
root->right = new TreeNode(30);
root->left->left = new TreeNode(40);
root->left->right = new TreeNode(60);
cout << diameterOfBinaryTree1(root) << endl;
cout << diameterOfBinaryTree2(root) << endl;
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t{1};
// cin >> t;
while (t--)
solve();
return 0;
} | 1,725 | 672 |
/**
* Created by Xiaozhong on 2020/11/27.
* Copyright (c) 2020/11/27 Xiaozhong. All rights reserved.
*/
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
char nextGreatestLetter(vector<char> &letters, char target) {
vector<char>::iterator iter = upper_bound(letters.begin(), letters.end(), target);
if (iter == letters.end()) iter = letters.begin();
return *iter;
}
};
int main() {
Solution s;
vector<char> letters = {'c', 'f', 'j'};
cout << s.nextGreatestLetter(letters, 'g') << endl;
cout << s.nextGreatestLetter(letters, 'j') << endl;
cout << s.nextGreatestLetter(letters, 'k') << endl;
} | 704 | 257 |
/***************************************************************************
* This file is part of the propertyEditor project *
* Copyright (C) 2008 by BogDan Vatra *
* bog_dan_ro@yahoo.com *
** GNU General Public License Usage **
* *
* This library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
** GNU Lesser General Public License **
* *
* 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 3 of the *
* License, or (at your option) any later version. *
* 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/>. *
* *
* 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 General Public License for more details. *
****************************************************************************/
#include <QtCore>
#include <QMetaProperty>
#include <QMetaEnum>
#include <QPushButton>
#include "stringlist.h"
#include "stringlisteditor.h"
//inline void initMyResource()
//{
// Q_INIT_RESOURCE(stringlist);
//}
StringList::StringList(QObject* parent, QObject* object, int property, const PropertyModel * propertyModel): PropertyInterface(parent, object, property, propertyModel)
{
// initMyResource();
}
QWidget* StringList::createEditor(QWidget * parent, const QModelIndex & index)
{
Q_UNUSED(index);
QPushButton * bt = new QPushButton(parent);
bt->setText(tr("Change stringlist"));
connect(bt, SIGNAL(pressed()), this, SLOT(buttonPressed()));
return bt;
}
void StringList::buttonPressed()
{
int result;
QStringList lst = StringListEditor::getStringList(0, value().toStringList(), &result);
if (result == QDialog::Accepted)
setValue(lst);
}
QVariant StringList::data(const QModelIndex & index)
{
if (!index.isValid() || !object() || -1 == objectProperty())
return QVariant();
switch (index.column())
{
case 0:
return object()->metaObject()->property(objectProperty()).name();
case 1:
QString s = "{" + value().toStringList().join(", ") + "}";
return s;
}
return QVariant();
}
bool StringList::setData(QVariant data, const QModelIndex & index)
{
Q_UNUSED(index);
return PropertyInterface::setValue(data);
}
bool StringList::canHandle(QObject * object, int property)const
{
if (object->metaObject()->property(property).isEnumType() || object->metaObject()->property(property).isFlagType())
return false;
switch (object->property(object->metaObject()->property(property).name()).type())
{
case QVariant::StringList:
return true;
default:
return false;
}
}
PropertyInterface* StringList::createInstance(QObject * object, int property, const PropertyModel * propertyModel) const
{
return new StringList(parent(), object, property, propertyModel);
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(StringListProperty, StringList)
#endif
| 4,164 | 1,137 |
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "astronomy/time_scales.hpp"
#include "astronomy/mercury_orbiter.hpp"
#include "base/array.hpp"
#include "base/file.hpp"
#include "base/not_null.hpp"
#include "base/pull_serializer.hpp"
#include "base/push_deserializer.hpp"
#include "base/serialization.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/interface.hpp"
#include "ksp_plugin/plugin.hpp"
#include "physics/discrete_trajectory.hpp"
#include "serialization/ksp_plugin.pb.h"
#include "testing_utilities/is_near.hpp"
#include "testing_utilities/serialization.hpp"
#include "testing_utilities/string_log_sink.hpp"
namespace principia {
namespace interface {
using astronomy::operator""_TT;
using astronomy::MercuryOrbiterInitialDegreesOfFreedom;
using astronomy::MercuryOrbiterInitialTime;
using astronomy::TTSecond;
using astronomy::date_time::DateTime;
using astronomy::date_time::operator""_DateTime;
using base::not_null;
using base::OFStream;
using base::ParseFromBytes;
using base::PullSerializer;
using base::PushDeserializer;
using ksp_plugin::Barycentric;
using ksp_plugin::Plugin;
using physics::DiscreteTrajectory;
using quantities::Speed;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Second;
using testing_utilities::operator""_⑴;
using testing_utilities::IsNear;
using testing_utilities::ReadFromBinaryFile;
using testing_utilities::ReadLinesFromBase64File;
using testing_utilities::ReadLinesFromHexadecimalFile;
using testing_utilities::StringLogSink;
using testing_utilities::WriteToBinaryFile;
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Not;
using ::testing::NotNull;
using ::testing::Pair;
using ::testing::SizeIs;
using ::testing::internal::CaptureStderr;
using ::testing::internal::GetCapturedStderr;
const char preferred_compressor[] = "gipfeli";
const char preferred_encoder[] = "base64";
class PluginCompatibilityTest : public testing::Test {
protected:
PluginCompatibilityTest()
: stderrthreshold_(FLAGS_stderrthreshold) {
google::SetStderrLogging(google::WARNING);
}
~PluginCompatibilityTest() override {
google::SetStderrLogging(stderrthreshold_);
}
// Reads a plugin from a file containing only the "serialized_plugin = "
// lines, with "serialized_plugin = " dropped.
static not_null<std::unique_ptr<Plugin const>> ReadPluginFromFile(
std::filesystem::path const& filename,
std::string_view const compressor,
std::string_view const encoder) {
Plugin const* plugin = nullptr;
PushDeserializer* deserializer = nullptr;
auto const lines =
encoder == "hexadecimal" ? ReadLinesFromHexadecimalFile(filename)
: encoder == "base64" ? ReadLinesFromBase64File(filename)
: std::vector<std::string>{};
CHECK(!lines.empty());
LOG(ERROR) << "Deserialization starting";
for (std::string const& line : lines) {
principia__DeserializePlugin(line.c_str(),
&deserializer,
&plugin,
compressor.data(),
encoder.data());
}
principia__DeserializePlugin("",
&deserializer,
&plugin,
compressor.data(),
encoder.data());
LOG(ERROR) << "Deserialization complete";
return std::unique_ptr<Plugin const>(plugin);
}
// Writes a plugin to a file.
static void WritePluginToFile(
std::filesystem::path const& filename,
std::string_view const compressor,
std::string_view const encoder,
not_null<std::unique_ptr<Plugin const>> plugin) {
OFStream file(filename);
PullSerializer* serializer = nullptr;
char const* b64 = nullptr;
LOG(ERROR) << "Serialization starting";
for (;;) {
b64 = principia__SerializePlugin(plugin.get(),
&serializer,
preferred_compressor,
preferred_encoder);
if (b64 == nullptr) {
break;
}
file << b64 << "\n";
principia__DeleteString(&b64);
}
LOG(ERROR) << "Serialization complete";
Plugin const* released_plugin = plugin.release();
principia__DeletePlugin(&released_plugin);
}
static void WriteAndReadBack(
not_null<std::unique_ptr<Plugin const>> plugin1) {
// Write the plugin to a new file with the preferred format.
WritePluginToFile(TEMP_DIR / "serialized_plugin.proto.b64",
preferred_compressor,
preferred_encoder,
std::move(plugin1));
// Read the plugin from the new file to make sure that it's fine.
auto plugin2 = ReadPluginFromFile(TEMP_DIR / "serialized_plugin.proto.b64",
preferred_compressor,
preferred_encoder);
}
static void CheckSaveCompatibility(std::filesystem::path const& filename,
std::string_view const compressor,
std::string_view const encoder) {
// Read a plugin from the given file.
auto plugin = ReadPluginFromFile(filename, compressor, encoder);
WriteAndReadBack(std::move(plugin));
}
int const stderrthreshold_;
};
TEST_F(PluginCompatibilityTest, PreCartan) {
// This space for rent.
}
TEST_F(PluginCompatibilityTest, PreCohen) {
StringLogSink log_warning(google::WARNING);
CheckSaveCompatibility(
SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3039.proto.hex",
/*compressor=*/"",
/*decoder=*/"hexadecimal");
EXPECT_THAT(
log_warning.string(),
AllOf(
HasSubstr(
"pre-Cohen ContinuousTrajectory"), // Regression test for #3039.
HasSubstr("pre-Cauchy"), // The save is even older.
Not(HasSubstr("pre-Cartan")))); // But not *that* old.
}
#if !_DEBUG
TEST_F(PluginCompatibilityTest, Reach) {
StringLogSink log_warning(google::WARNING);
not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile(
SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3072.proto.b64",
/*compressor=*/"gipfeli",
/*decoder=*/"base64");
EXPECT_THAT(log_warning.string(),
AllOf(HasSubstr("pre-Galileo"), Not(HasSubstr("pre-Frobenius"))));
auto const test = plugin->GetVessel("f2d77873-4776-4809-9dfb-de9e7a0620a6");
EXPECT_THAT(test->name(), Eq("TEST"));
EXPECT_THAT(TTSecond(test->history()->front().time),
Eq("1970-08-14T08:03:18"_DateTime));
EXPECT_THAT(TTSecond(test->psychohistory()->back().time),
Eq("1970-08-14T08:47:05"_DateTime));
EXPECT_FALSE(test->has_flight_plan());
auto const ifnity = plugin->GetVessel("29142a79-7acd-47a9-a34d-f9f2a8e1b4ed");
EXPECT_THAT(ifnity->name(), Eq("IFNITY-5.2"));
EXPECT_THAT(TTSecond(ifnity->history()->front().time),
Eq("1970-08-14T08:03:46"_DateTime));
EXPECT_THAT(TTSecond(ifnity->psychohistory()->back().time),
Eq("1970-08-14T08:47:05"_DateTime));
ASSERT_TRUE(ifnity->has_flight_plan());
EXPECT_THAT(ifnity->flight_plan().number_of_manœuvres(), Eq(16));
std::vector<std::pair<DateTime, Speed>> manœuvre_ignition_tt_seconds_and_Δvs;
for (int i = 0; i < ifnity->flight_plan().number_of_manœuvres(); ++i) {
manœuvre_ignition_tt_seconds_and_Δvs.emplace_back(
TTSecond(ifnity->flight_plan().GetManœuvre(i).initial_time()),
ifnity->flight_plan().GetManœuvre(i).Δv().Norm());
}
// The flight plan only covers the inner solar system (this is probably
// because of #3035).
// It also differs from https://youtu.be/7BDxZV7UD9I?t=439.
// TODO(egg): Compute the flybys and figure out what exactly is going on in
// this flight plan.
EXPECT_THAT(manœuvre_ignition_tt_seconds_and_Δvs,
ElementsAre(Pair("1970-08-14T09:34:49"_DateTime,
3.80488671073918022e+03 * (Metre / Second)),
Pair("1970-08-15T13:59:24"_DateTime,
3.04867185471741759e-04 * (Metre / Second)),
Pair("1970-12-22T07:48:21"_DateTime,
1.58521291818444873e-03 * (Metre / Second)),
Pair("1971-01-08T17:36:55"_DateTime,
1.40000000034068623e-03 * (Metre / Second)),
Pair("1971-07-02T17:16:00"_DateTime,
1.00000000431022681e-04 * (Metre / Second)),
Pair("1971-09-06T03:27:33"_DateTime,
1.78421858738381537e-03 * (Metre / Second)),
Pair("1972-02-13T22:47:26"_DateTime,
7.72606625794511597e-04 * (Metre / Second)),
Pair("1972-03-25T16:30:19"_DateTime,
5.32846131747503372e-03 * (Metre / Second)),
Pair("1972-12-24T04:09:32"_DateTime,
3.45000000046532824e-03 * (Metre / Second)),
Pair("1973-06-04T01:59:07"_DateTime,
9.10695453328359134e-03 * (Metre / Second)),
Pair("1973-07-09T06:07:17"_DateTime,
4.49510921430966881e-01 * (Metre / Second)),
Pair("1973-09-10T03:59:44"_DateTime,
1.00000000431022681e-04 * (Metre / Second)),
Pair("1974-11-20T17:34:27"_DateTime,
5.10549409572428781e-01 * (Metre / Second)),
Pair("1975-10-07T01:29:45"_DateTime,
2.86686518692948443e-02 * (Metre / Second)),
Pair("1975-12-29T21:27:13"_DateTime,
1.00404183285598275e-03 * (Metre / Second)),
Pair("1977-07-28T22:47:53"_DateTime,
1.39666705839172456e-01 * (Metre / Second))));
// Make sure that we can upgrade, save, and reload.
WriteAndReadBack(std::move(plugin));
}
#endif
TEST_F(PluginCompatibilityTest, DISABLED_Butcher) {
StringLogSink log_warning(google::WARNING);
not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile(
R"(P:\Public Mockingbird\Principia\Saves\1119\1119.proto.b64)",
/*compressor=*/"gipfeli",
/*decoder=*/"base64");
EXPECT_THAT(log_warning.string(),
AllOf(HasSubstr("pre-Haar"), Not(HasSubstr(u8"pre-Gröbner"))));
auto const& orbiter =
*plugin->GetVessel("e180ca12-492f-45bf-a194-4c5255aec8a0");
EXPECT_THAT(orbiter.name(), Eq("Mercury Orbiter 1"));
auto const begin = orbiter.history()->begin();
EXPECT_THAT(begin->time,
Eq("1966-05-10T00:14:03"_TT + 0.0879862308502197 * Second));
EXPECT_THAT(begin->degrees_of_freedom,
Eq(DegreesOfFreedom<Barycentric>(
Barycentric::origin + Displacement<Barycentric>(
{-9.83735958466250000e+10 * Metre,
-1.05659916408781250e+11 * Metre,
-4.58171358797500000e+10 * Metre}),
Velocity<Barycentric>(
{+2.18567382812500000e+04 * (Metre / Second),
-1.76616533203125000e+04 * (Metre / Second),
-7.76112133789062500e+03 * (Metre / Second)}))));
auto const& mercury = plugin->GetCelestial(2);
EXPECT_THAT(mercury.body()->name(), Eq("Mercury"));
plugin->RequestReanimation(begin->time);
while (mercury.trajectory().t_min() > begin->time) {
absl::SleepFor(absl::Milliseconds(1));
}
// The history goes back far enough that we are still on our way to Mercury at
// the beginning.
EXPECT_THAT((begin->degrees_of_freedom.position() -
mercury.trajectory().EvaluatePosition(begin->time)).Norm(),
IsNear(176'400'999_⑴ * Kilo(Metre)));
EXPECT_THAT(begin->time,
Eq("1966-05-10T00:14:03"_TT + 0.0879862308502197 * Second));
EXPECT_THAT(begin->degrees_of_freedom,
Eq(DegreesOfFreedom<Barycentric>(
Barycentric::origin + Displacement<Barycentric>(
{-9.83735958466250000e+10 * Metre,
-1.05659916408781250e+11 * Metre,
-4.58171358797500000e+10 * Metre}),
Velocity<Barycentric>(
{+2.18567382812500000e+04 * (Metre / Second),
-1.76616533203125000e+04 * (Metre / Second),
-7.76112133789062500e+03 * (Metre / Second)}))));
// We arrive in late August. Check the state in the beginning of September.
auto const it = orbiter.trajectory().lower_bound("1966-09-01T00:00:00"_TT);
EXPECT_THAT(it->time, Eq(MercuryOrbiterInitialTime));
EXPECT_THAT(it->degrees_of_freedom,
Eq(MercuryOrbiterInitialDegreesOfFreedom<Barycentric>));
EXPECT_THAT((it->degrees_of_freedom.position() -
mercury.trajectory().EvaluatePosition(it->time)).Norm(),
IsNear(19'163_⑴ * Kilo(Metre)));
// Make sure that we can upgrade, save, and reload.
WriteAndReadBack(std::move(plugin));
}
TEST_F(PluginCompatibilityTest, DISABLED_Lpg) {
StringLogSink log_warning(google::WARNING);
not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile(
R"(P:\Public Mockingbird\Principia\Saves\3136\3136.proto.b64)",
/*compressor=*/"gipfeli",
/*decoder=*/"base64");
EXPECT_THAT(log_warning.string(),
AllOf(HasSubstr("pre-Hamilton"), Not(HasSubstr("pre-Haar"))));
// The vessel with the longest history.
auto const& vessel =
*plugin->GetVessel("77ddea45-47ee-48c0-aee9-d55cdb35ffcd");
auto history = vessel.history();
auto psychohistory = vessel.psychohistory();
EXPECT_THAT(*history, SizeIs(435'927));
EXPECT_THAT(*psychohistory, SizeIs(3));
// Evaluate a point in each of the two segments.
EXPECT_THAT(history->EvaluateDegreesOfFreedom("1957-10-04T19:28:34"_TT),
Eq(DegreesOfFreedom<Barycentric>(
Barycentric::origin + Displacement<Barycentric>(
{+1.47513683827317657e+11 * Metre,
+2.88696086355042419e+10 * Metre,
+1.24740082262952404e+10 * Metre}),
Velocity<Barycentric>(
{-6.28845231836519179e+03 * (Metre / Second),
+2.34046542233168329e+04 * (Metre / Second),
+4.64410011408655919e+03 * (Metre / Second)}))));
EXPECT_THAT(psychohistory->EvaluateDegreesOfFreedom("1958-10-07T09:38:30"_TT),
Eq(DegreesOfFreedom<Barycentric>(
Barycentric::origin + Displacement<Barycentric>(
{+1.45814173315801941e+11 * Metre,
+3.45409490426372147e+10 * Metre,
+1.49445864962450924e+10 * Metre}),
Velocity<Barycentric>(
{-8.70708379504568074e+03 * (Metre / Second),
+2.61488327506437054e+04 * (Metre / Second),
+1.90319283138508908e+04 * (Metre / Second)}))));
// Serialize the history and psychohistory to a temporary file.
{
serialization::DiscreteTrajectory message;
vessel.trajectory().WriteToMessage(
&message, /*tracked=*/{history, psychohistory}, /*exact=*/{});
auto const serialized_message = base::SerializeAsBytes(message);
WriteToBinaryFile(TEMP_DIR / "trajectory_3136.proto.bin",
serialized_message.get());
}
// Deserialize the temporary file to make sure that it's valid.
{
auto const serialized_message =
ReadFromBinaryFile(TEMP_DIR / "trajectory_3136.proto.bin");
auto const message =
ParseFromBytes<serialization::DiscreteTrajectory>(serialized_message);
auto const trajectory = DiscreteTrajectory<Barycentric>::ReadFromMessage(
message, /*tracked=*/{&history, &psychohistory});
EXPECT_THAT(*history, SizeIs(435'927));
EXPECT_THAT(*psychohistory, SizeIs(3));
}
// Make sure that we can upgrade, save, and reload.
WriteAndReadBack(std::move(plugin));
}
TEST_F(PluginCompatibilityTest, DISABLED_Egg) {
StringLogSink log_warning(google::WARNING);
not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile(
R"(P:\Public Mockingbird\Principia\Saves\3136\3136b.proto.b64)",
/*compressor=*/"gipfeli",
/*decoder=*/"base64");
EXPECT_THAT(log_warning.string(),
AllOf(HasSubstr("pre-Hamilton"), Not(HasSubstr("pre-Haar"))));
auto& mutable_plugin = const_cast<Plugin&>(*plugin);
// This would fail if segment iterators were invalidated during part
// deserialization.
mutable_plugin.AdvanceTime(
mutable_plugin.GameEpoch() + 133218.91123694609 * Second,
295.52698460805016 * Degree);
mutable_plugin.CatchUpVessel("1e07aaa2-d1f8-4f6d-8b32-495b46109d98");
// Make sure that we can upgrade, save, and reload.
WriteAndReadBack(std::move(plugin));
}
// Use for debugging saves given by users.
TEST_F(PluginCompatibilityTest, DISABLED_SECULAR_Debug) {
not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile(
R"(P:\Public Mockingbird\Principia\Saves\3203\wip.proto.b64)",
/*compressor=*/"gipfeli",
/*decoder=*/"base64");
}
} // namespace interface
} // namespace principia
| 18,068 | 6,742 |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2008 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ql/time/calendars/bespokecalendar.hpp>
#include <sstream>
namespace QuantLib {
BespokeCalendar::Impl::Impl(const std::string& name)
: name_(name) {}
std::string BespokeCalendar::Impl::name() const {
return name_;
}
bool BespokeCalendar::Impl::isWeekend(Weekday w) const {
return (weekend_.find(w) != weekend_.end());
}
bool BespokeCalendar::Impl::isBusinessDay(const Date& date) const {
return !isWeekend(date.weekday());
}
void BespokeCalendar::Impl::addWeekend(Weekday w) {
weekend_.insert(w);
}
BespokeCalendar::BespokeCalendar(const std::string& name) {
bespokeImpl_ = std::make_shared<BespokeCalendar::Impl>(name);
impl_ = bespokeImpl_;
}
void BespokeCalendar::addWeekend(Weekday w) {
bespokeImpl_->addWeekend(w);
}
}
| 1,661 | 547 |
#include <algorithm>
#include <vector>
#include <deque>
class Solution {
private:
void BFS(std::vector<std::vector<int>>& G, std::deque<std::pair<int, int>>& Q, std::vector<bool>& visited, std::pair<int, int> &res)
{
if (Q.empty()) return;
auto front = Q.front();
Q.pop_front();
if (!visited[front.first]) {
visited[front.first] = true;
res = front;
for (auto next : G[front.first]) {
Q.push_back(std::make_pair(next, 1 + front.second));
}
}
BFS(G, Q, visited, res);
}
void MHT(std::vector<std::vector<int>>& G, std::deque<std::pair<int, int>>& Q,
std::vector<bool>& visited, int depth, std::vector<std::pair<int, int>>& res)
{
if (Q.empty()) return;
auto front = Q.front();
Q.pop_front();
if (!visited[front.first]) {
visited[front.first] = true;
// printf("visiting: %d %d\n", front.first, front.second);
if (depth & 1) {
if (front.second == depth / 2 || front.second == 1 + depth / 2)
res.push_back(front);
} else {
if (front.second == depth / 2)
res.push_back(front);
}
for (auto next : G[front.first]) {
Q.push_back(std::make_pair(next, 1 + front.second));
}
}
MHT(G, Q, visited, depth, res);
}
void showGraph(std::vector<std::vector<int>>& G) {
for (int i = 0; i < (int)G.size(); i++) {
printf("%d ->", i);
for (auto x : G[i]) {
printf(" %d", x);
}
printf("\n");
}
}
public:
std::vector<int> findMinHeightTrees(int n, std::vector<std::pair<int, int>>& edges)
{
std::vector<int> res;
std::vector<std::pair<int, int>> v1, v2;
std::vector<std::vector<int>> G;
std::deque<std::pair<int, int>> Q;
std::vector<bool>V;
std::pair<int, int> last, first;
int depth;
G.resize(n);
V.resize(n);
for (auto it = edges.begin(); it != edges.end(); ++it) {
G[it->first].push_back(it->second);
G[it->second].push_back(it->first);
}
Q.push_back(std::make_pair(0, 0));
BFS(G, Q, V, last);
V.clear();
Q.clear();
V.resize(n);
Q.push_back(std::make_pair(last.first, 0));
BFS(G, Q, V, first);
depth = first.second;
V.clear();
V.resize(n);
Q.clear();
Q.push_back(std::make_pair(first.first, 0));
MHT(G, Q, V, depth, v1);
V.clear();
V.resize(n);
Q.clear();
Q.push_back(std::make_pair(last.first, 0));
MHT(G, Q, V, depth, v2);
for (auto x : v1) {
for (auto y : v2) {
// printf("x (%d %d), y (%d %d)\n", x.first, x.second, y.first, y.second);
if (x.first == y.first) {
if (!(depth & 1)) {
if (x.second == y.second && x.second == depth / 2)
res.push_back(x.first);
} else {
if ( (x.second == depth / 2 && y.second == 1 + depth / 2) ||
(x.second == 1 + depth / 2 && y.second == depth / 2) ) {
res.push_back(x.first);
}
}
}
}
}
// showGraph(G);
return res;
}
};
int main(int argc, char* argv[])
{
std::vector<std::pair<int, int>> G;
Solution S;
int n;
int x, y;
scanf("%d\n", &n);
while(!feof(stdin)) {
scanf("%d %d\n", &x, &y);
G.push_back(std::make_pair(x, y));
}
auto res = S.findMinHeightTrees(n, G);
for (auto x : res) {
printf("%d\n", x);
}
return 0;
}
| 3,295 | 1,387 |
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2017 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel 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 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 INTEL OR
ITS 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.
END_LEGAL */
#include <cstdio>
#include <cstdlib>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using std::string;
extern "C" void TellPinSectionCount(int sectionCount)
{
// Pin tool can place instrumentation here to learn sections count.
}
int GetSectionCount(string command)
{
string result, file, word;
FILE* output(popen(command.c_str(), "r"));
char buffer[256];
std::vector<string> vec;
while(fgets(buffer, sizeof(buffer), output) != NULL)
{
file = buffer;
result += file.substr(0, file.size() - 1);
}
std::istringstream iss(result);
while (iss >> word)
{
vec.push_back(word);
}
pclose(output);
return atoi(vec.back().c_str());
}
int main(int argc, char** argv)
{
int sectionCount = 0;
string imgName(argv[0]);
sectionCount = GetSectionCount("readelf -h " + imgName + " | grep 'Number of section headers'");
TellPinSectionCount(sectionCount);
return 0;
}
| 2,524 | 861 |
#include "storm/builder/jit/JitModelBuilderInterface.h"
#include "storm/adapters/RationalFunctionAdapter.h"
namespace storm {
namespace builder {
namespace jit {
template <typename IndexType, typename ValueType>
JitModelBuilderInterface<IndexType, ValueType>::JitModelBuilderInterface(ModelComponentsBuilder<IndexType, ValueType>& modelComponentsBuilder) : modelComponentsBuilder(modelComponentsBuilder) {
// Intentionally left empty.
}
template <typename IndexType, typename ValueType>
JitModelBuilderInterface<IndexType, ValueType>::~JitModelBuilderInterface() {
// Intentionally left empty.
}
template <typename IndexType, typename ValueType>
void JitModelBuilderInterface<IndexType, ValueType>::addStateBehaviour(IndexType const& stateId, StateBehaviour<IndexType, ValueType>& behaviour) {
modelComponentsBuilder.addStateBehaviour(stateId, behaviour);
}
template class JitModelBuilderInterface<uint32_t, double>;
template class JitModelBuilderInterface<uint32_t, storm::RationalNumber>;
template class JitModelBuilderInterface<uint32_t, storm::RationalFunction>;
}
}
}
| 1,344 | 326 |
//=========================================================================
// 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.
//=========================================================================
#include "smtk/io/ImportMesh.h"
#include "smtk/mesh/core/Resource.h"
#include "smtk/mesh/testing/cxx/helpers.h"
namespace
{
//SMTK_DATA_DIR is a define setup by cmake
std::string data_root = SMTK_DATA_DIR;
void verify_import_unstructured_grid()
{
smtk::mesh::ResourcePtr c = smtk::mesh::Resource::create();
std::string file_path(data_root);
file_path += "/mesh/3d/nickel_superalloy.vtu";
test(smtk::io::importMesh(file_path, c), "should be able to import unstructured grid");
}
void verify_import_polydata()
{
smtk::mesh::ResourcePtr c = smtk::mesh::Resource::create();
std::string file_path(data_root);
file_path += "/scene/BasicScene_12_20_07/PolygonMesh_f8e612a9-876c-4145-9c74-ee6c39f2a157.vtp";
test(smtk::io::importMesh(file_path, c), "should be able to import polydata");
}
} // namespace
int UnitTestMeshIOVTK(int argc, char* argv[])
{
(void)argc;
(void)argv;
verify_import_unstructured_grid();
verify_import_polydata();
return 0;
}
// This macro ensures the vtk io library is loaded into the executable
smtkComponentInitMacro(smtk_extension_vtk_io_mesh_MeshIOVTK)
| 1,565 | 581 |
//
// Created by GasparQ on 03/04/2018.
//
#include <cassert>
#include <iostream>
#include <typeinfo>
#include "Cerealizable/Scalar.hpp"
#include "Cerealizable/List.hpp"
#include "Cerealizable/Tuple.hpp"
#include "Cerealizable/Object.hpp"
#include "Cerealizer/Binary/Binary.hpp"
#include "Cerealizer/JSON/JSON.hpp"
using namespace Cerealization;
template <typename Cerealizer, typename Data>
bool test_cerealize(Data const &toser)
{
Cerealizer cerealizer;
Data witness;
std::string dataname(typeid(Data).name());
std::string cername(typeid(Cerealizer).name());
std::cout << "Cerealizing " << dataname.substr(31) << " into " << cername.substr(30) << " ===> ";
cerealizer << toser;
if (std::is_same<std::string, decltype(cerealizer.Data())>::value)
std::cout << cerealizer.Data() << " ===> ";
cerealizer >> witness;
if (toser == witness)
{
std::cout << "Success" << std::endl;
return true;
}
std::cout << "Failure" << std::endl;
return false;
}
template <typename Cerealizer>
void test_scalar()
{
assert(test_cerealize<Cerealizer>(Cerealizable::Char('t')));
assert(test_cerealize<Cerealizer>(Cerealizable::Char(-128)));
assert(test_cerealize<Cerealizer>(Cerealizable::UChar('t')));
assert(test_cerealize<Cerealizer>(Cerealizable::UChar(255)));
assert(test_cerealize<Cerealizer>(Cerealizable::Short(-42)));
assert(test_cerealize<Cerealizer>(Cerealizable::UShort(42)));
assert(test_cerealize<Cerealizer>(Cerealizable::Int(-2000000000)));
assert(test_cerealize<Cerealizer>(Cerealizable::UInt(4000000000)));
assert(test_cerealize<Cerealizer>(Cerealizable::Long(-2000000000)));
assert(test_cerealize<Cerealizer>(Cerealizable::ULong(4000000000)));
assert(test_cerealize<Cerealizer>(Cerealizable::LongLong(-8000000000000000000)));
assert(test_cerealize<Cerealizer>(Cerealizable::ULongLong(9000000000000000000)));
assert(test_cerealize<Cerealizer>(Cerealizable::Float(50.3f)));
assert(test_cerealize<Cerealizer>(Cerealizable::Float(-50.3f)));
assert(test_cerealize<Cerealizer>(Cerealizable::Double(50.3)));
assert(test_cerealize<Cerealizer>(Cerealizable::Double(-50.3)));
}
template <typename Cerealizer>
void test_list()
{
assert(test_cerealize<Cerealizer>(Cerealizable::String("Coucou")));
std::string toto("coucou");
assert(test_cerealize<Cerealizer>(Cerealizable::String(toto)));
assert(test_cerealize<Cerealizer>(Cerealizable::List<int>({3, 1, 20})));
assert(test_cerealize<Cerealizer>(
Cerealizable::List<Cerealizable::String>(
{
Cerealizable::String("hey"),
Cerealizable::String("ho"),
Cerealizable::String("hello")
}
)));
assert(test_cerealize<Cerealizer>(Cerealizable::Vector<int>({3, 1, 20})));
assert(test_cerealize<Cerealizer>(
Cerealizable::Vector<Cerealizable::String>(
{
Cerealizable::String("hey"),
Cerealizable::String("ho"),
Cerealizable::String("hello")
}
)));
assert(test_cerealize<Cerealizer>(Cerealizable::Set <int>({3, 1, 20})));
assert(test_cerealize<Cerealizer>(Cerealizable::Set <std::string>({ "hey", "ho", "hello" })));
assert(test_cerealize<Cerealizer>(Cerealizable::Map <char, int>({ {'j', 3}, {'l', 1}, {'i', 20} })));
assert(test_cerealize<Cerealizer>(
Cerealizable::Map <std::string, Cerealizable::String>(
{
{"hey", Cerealizable::String("hey")},
{"ho", Cerealizable::String("ho")},
{"hello", Cerealizable::String("hello")}
}
)));
assert(test_cerealize<Cerealizer>(Cerealizable::List<Tuple<int, String, Int>>{
Tuple<int, String, Int>(43, String("toto"), 50),
Tuple<int, String, Int>(78, String("tutu"), 90),
Tuple<int, String, Int>(-78, String("tata"), 120),
Tuple<int, String, Int>(-388, String("titi"), -3920)
}));
}
template <typename Cerealizer>
void test_tuple()
{
assert(test_cerealize<Cerealizer>(Tuple<int, int, int>(-43, 29, 39)));
assert(test_cerealize<Cerealizer>(Tuple<int, char, double>(-43, 'd', 3.14)));
assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, char, double>(-43, 'd', 3.14)));
assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, double>(-43, String("Coucou"), 3.14)));
assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, Tuple<int, int, int>>(-43, String("Coucou"), Tuple<int, int, int>(3, -42, 39))));
assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, Tuple<int, String, int>>(-43, String("Coucou"), Tuple<int, String, int>(3, String("C'est moit"), 39))));
}
template <typename Cerelizer>
void test_object()
{
assert(test_cerealize<Cerelizer>(Object<int, int, int>({"x", 42}, {"y", -42}, {"z", 390})));
assert(test_cerealize<Cerelizer>(Object<int, char, double>({"x", 42}, {"id", 'k'}, {"radius", 3.14})));
assert(test_cerealize<Cerelizer>(Object<Scalar<int>, char, double>({"x", 42}, {"id", 'k'}, {"radius", 3.14})));
assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, double>({"x", 42}, {"id", String("Toto")}, {"radius", 3.14})));
assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, Tuple<int, int, int>>({"x", 42}, {"id", String("Toto")}, {"radius", Tuple<int, int, int>(3, -42, 39)})));
assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, Tuple<int, String, int>>({"x", 42}, {"id", String("Toto")}, {"radius", Tuple<int, String, int>(3, String("C'est moi"), 39)})));
}
int main()
{
test_scalar<Cerealizer::BinaryStream>();
test_scalar<Cerealizer::JSONStream>();
test_list<Cerealizer::BinaryStream>();
test_list<Cerealizer::JSONStream>();
test_tuple<Cerealizer::BinaryStream>();
test_tuple<Cerealizer::JSONStream>();
test_object<Cerealizer::BinaryStream>();
test_object<Cerealizer::JSONStream>();
return 0;
} | 5,965 | 2,391 |
#include "defines.h"
#include "ff_gen_drv.h"
const Diskio_drvTypeDef USBH_Driver{ 0, 0, 0 };
uint8_t FATFS_LinkDriver(const Diskio_drvTypeDef * /*drv*/, char * /*path*/)
{
return 0;
}
uint8_t FATFS_UnLinkDriver(char * /*path*/)
{
return 0;
}
| 257 | 124 |
#include "AncillaryDataEvent/Recon.h"
#include <algorithm>
//using namespace AncillaryData;
namespace AncillaryData {
Recon::Recon(AncillaryData::Digi *digiEvent)
{
setEventNumber(digiEvent->getEventNumber());
setSpillNumber(digiEvent->getSpillNumber());
setQdcHitCol(digiEvent->getQdcHitCol());
setScalerHitCol(digiEvent->getScalerHitCol());
PX = -9999.0; PY= -9999.0; PZ= -9999.0;
E_rec=0;
E_corr=0;
PhiIn=-100;
PhiOut=-100;
Dphi=-100;
Theta=-100;
m_NumberHigestClusters=0;
m_NumberTotalClusters=0;
for(unsigned int m=0; m < N_MODULES; m++)
{
m_NumberClusters[0][m]=0;
m_NumberClusters[1][m]=0;
}
}
void Recon::print()
{
std::cout<< " Ancillary Recon Event: "<<getEventNumber()<<" Spill Number: "<<getSpillNumber()<<std::endl;
std::cout<< " --- number of Tagger Clusters: "<<m_taggerClusterCol.size()<<std::endl;
for(std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin(); pos!=m_taggerClusterCol.end(); ++pos)
(*pos).print();
std::cout<< " --- number of QDC Hits : "<<m_qdcHitCol.size()<<std::endl;
for(std::vector<QdcHit>::iterator pos= m_qdcHitCol.begin(); pos!= m_qdcHitCol.end(); ++pos)
(*pos).print();
std::cout<< " --- number of Scaler Hits : "<<m_scalerHitCol.size()<<std::endl;
for(std::vector<ScalerHit>::iterator pos= m_scalerHitCol.begin(); pos!= m_scalerHitCol.end(); ++pos)
(*pos).print();
}
void Recon::ComputeClustersProperties()
{
for(std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin(); pos!=m_taggerClusterCol.end(); ++pos)
(*pos).calculateProperties();
}
std::vector<TaggerCluster> Recon::GetHighestClusters()
{
SortClusters();
for(unsigned int m=0;m < N_MODULES;m++)
{
m_NumberClusters[0][m]=0;
m_NumberClusters[1][m]=0;
}
// std::cout<<"std::vector<TaggerCluster> Recon::GetHighestClusters: "<<m_taggerClusterCol.size()<<std::endl;
// m_NumberClusters = m_taggerClusterCol.size();
if(m_taggerClusterCol.size()<=1)
return m_taggerClusterCol;
std::vector<TaggerCluster> HigestsClusters;
///////
for(std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin(); pos<m_taggerClusterCol.end();pos++)
m_NumberClusters[(*pos).getLayerId()][(*pos).getModuleId()]++;
m_NumberTotalClusters = 0;
for(unsigned int m=0; m < N_MODULES; m++)
{
m_NumberTotalClusters += m_NumberClusters[0][m];
m_NumberTotalClusters += m_NumberClusters[1][m];
}
//////
std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin();
TaggerCluster selectedCluster=(*pos);
pos++;
while(pos<m_taggerClusterCol.end())
{
TaggerCluster newCluster=(*pos);
// std::cout<<"selected cluster:"<<selectedCluster.getModuleId()<<", "<<selectedCluster.getLayerId()<<std::endl;
// std::cout<<"new Cluster cluster:"<<newCluster.getModuleId()<<", "<<newCluster.getLayerId()<<std::endl;
if(selectedCluster.getModuleId()==newCluster.getModuleId() &&
selectedCluster.getLayerId()==newCluster.getLayerId())
{
selectedCluster=MaxCluster(newCluster,selectedCluster);
}
else
{
HigestsClusters.push_back(selectedCluster);
selectedCluster=newCluster;
}
pos++;
}
HigestsClusters.push_back(selectedCluster);
m_NumberHigestClusters=HigestsClusters.size();
// std::cout<<"std::vector<TaggerCluster> Recon::GetHighestClusters m_NumberHigestClusters "<<m_NumberHigestClusters<<std::endl;
return HigestsClusters;
}
void Recon::SortClusters()
{
std::sort(m_taggerClusterCol.begin(),m_taggerClusterCol.end(),ClusterSortPredicate);
}
void Recon::computePositions(AncillaryGeometry *geometry)
{
std::vector<TaggerCluster> higestClusters = GetHighestClusters();
for (unsigned int i = 0 ; i < N_MODULES ; i++)
{
X[i] = 0.0; Y[i] = 0.0; Z[i] = 0.0;
}
for(std::vector<TaggerCluster>::iterator pos=higestClusters.begin();pos!=higestClusters.end(); ++pos)
{
const unsigned int M= (*pos).getModuleId();
const unsigned int L= (*pos).getLayerId(); // 0 or 1
// View and direction of the first view
unsigned int V,D;
if(L==0)
{
V = geometry->getView1(M);
D = geometry->getDirection1(M);
}
else
{
V = geometry->getView2(M);
D = geometry->getDirection2(M);
}
const double HalfWafer = N_CHANNELS_PER_LAYER*STRIPS_PITCH/2.0;
// this is valid for both views:
X[M] = geometry->getX(M);
// case of first view
if(V==1 && D == 0) // case : V = Z, D = +
Z[M] = geometry->getZ(M) - HalfWafer + (*pos).getPosition();
else if(V==1 && D == 1 ) // case : V = Z, D = -
Z[M] = geometry->getZ(M) + HalfWafer - (*pos).getPosition();
else if(V==0 && D == 0) // case : V = Y, D = +
Y[M] = geometry->getY(M) - HalfWafer + (*pos).getPosition();
else if(V==0 && D == 1 ) // case : V = Y, D = -
Y[M] = geometry->getY(M) + HalfWafer - (*pos).getPosition();
}
}
void Recon::reconstructEnergy(AncillaryGeometry *geometry)
{
E_rec = 0.0;
E_corr = 0.0;
double bt=geometry->getBL();
double beamMomentum=geometry->getBeamMomentum()*1000.0; //MeV
// first track:
const double Dist1 = X[1]-X[0];
const double Disp1 = Y[1]-Y[0];
const double Dist2 = X[3]-X[2];
const double Disp2 = Y[3]-Y[2];
double a1,a2,b1,b2;
if(Disp1!=0)
{
a1 = Disp1/Dist1;
b1 = (Y[0]*X[1]-Y[1]*X[0])/Dist1;
PhiIn = atan2(Disp1,Dist1);
}
if(Disp2!=0)
{
// r1 = a2*x + b2
a2 = Disp2/Dist2;
b2 = (Y[2]*X[3]-Y[3]*X[2])/Dist2;
PhiOut = atan2(Disp2,Dist2);
}
if(Disp1!=0 && Disp2!=0 )
{
Dphi = PhiOut - PhiIn;
double phiErrIn = STRIPS_PITCH/Dist1;
double phiErrOut = STRIPS_PITCH/Dist2;
// double DphiErr = sqrt(phiErrIn*phiErrIn+phiErrOut*phiErrOut);
if(fabs(sin(PhiOut)-sin(PhiIn))>0)
{
E_rec = beamMomentum - (300.*bt/(sin(PhiOut)-sin(PhiIn)));
Error_E_rec = (300.*bt/pow(sin(PhiOut)-sin(PhiIn),2.0)*sqrt(pow(cos(PhiOut)*phiErrOut,2.0)+pow(cos(PhiIn)*phiErrIn,2.0)));
if(fabs(a1-a2)>0)
{
PX = (b2-b1)/(a1-a2);
PY = a1 * PX + b1;
}
}
// Z = A* X + B
// Case with two points in z:
if(m_NumberHigestClusters==8 && m_NumberTotalClusters == 8)
{
double SX = X[0]+X[1]+X[2]+X[3];
double SZ = Z[0]+Z[1]+Z[2]+Z[3];
double SXX = X[0]*X[0] + X[1]*X[1] + X[2]*X[2] + X[3]*X[3];
double SZX = Z[0]*X[0] + Z[1]*X[1] + Z[2]*X[2] + Z[3]*X[3];
double A = (4.*SZX-SZ*SX)/(4.*SXX-SX*SX);
double B = (SZ-A*SX)/4.;
if(fabs(a1-a2)>0) PZ = A * PX + B;
Theta=atan2(4.*SZX-SZ*SX,4.*SXX-SX*SX);
if(fabs(cos(Theta))>0)
{
E_corr = E_rec/cos(Theta);
Error_E_corr=Error_E_rec;
}
}
}
}
void Recon::report()
{
std::cout<<" RECON EVENT REPORT: Total Clusters: "<<m_NumberTotalClusters<<" Higest:" <<m_NumberHigestClusters<<std::endl;
{
const double Disp1 = Y[1]-Y[0];
const double Disp2 = Y[3]-Y[2];
if(Disp1!=0)
std::cout<<" Electron Incoming Angle: \t"<<PhiIn<<std::endl;
if(Disp2!=0)
std::cout<<" Electron Outgoing Angle: \t"<<PhiOut<<std::endl;
if(Disp1!=0 && Disp2!=0)
{
std::cout<<" Delta angle : \t"<<Dphi<<std::endl;
std::cout<<" Reconstructed Energy : \t"<<E_rec<<" +- "<< Error_E_rec <<std::endl;
if(m_NumberHigestClusters==8 && m_NumberTotalClusters == 8)
{
std::cout<<" Theta Angle : \t"<<Theta<<std::endl;
std::cout<<" Corrected Energy : \t"<<E_corr<<" +- "<< Error_E_corr <<std::endl;
}
std::cout<<" Intesection Point "<<std::endl;
std::cout<<" \t X \t Y \t Z "<<std::endl;
std::cout<<" \t "<<PX<<" \t "<<PY<<" \t "<<PZ<<std::endl;
std::cout<<" Higest Selected Clusters: "<<std::endl;
}
std::cout<<" \t X \t Y \t Z "<<std::endl;
for(unsigned int m=0; m < N_MODULES; m++)
std::cout<<" \t "<<X[m]<<" \t "<<Y[m]<<" \t "<<Z[m]<<std::endl;
/*
std::cout<<" Sorry, not enough clusters!"<<std::endl;
std::cout<<" M = "<<m<<" Num Clusters: L = 0: "<< m_NumberClusters[0][m]<<" L = 1: "<<m_NumberClusters[1][m]<<std::endl;
*/
}
}
} // end namespace AncillaryData
/*
AD_TIMESTAMP Trigger Time-stamp measured in the AD system
AD_PID particle ID code from AD data (use same as G4 particle code?)
TAG_PHI_IN electron incoming angle before magnet measured by silicon chambers 1 and 2 in the bending plane
TAG_THETA_IN electron incoming angle before magnet measured by silicon chambers 1 and 2 in the bending plane
TAG_XYZ[3,4] X,Y,Z coordinates of highest cluster in each of the four silicon tagger station
TAG_XYZ_IN_CU[3] X,Y,Z coordinates of photon impact point on CU (assuming photon collinear with e beam)
TAG_DPHI electron deflection angle after magnet in the bending plane
TAG_EGAMMA photon energy (Ebeam - Edeflected_electron)
TAG_EGAMMA_ERR error on photon energy measuement
CRNKV_PHA[2] pulse height amplitude in the 2 cerenkov
SCINT_PHA[8] array of floats - PHA for scintillators in the setup (8 is a placeholder for a reasonable number, might change)
TRD_NUM[16]
void Recon::computeFinalTupla()
{
}
*/
| 9,367 | 3,957 |
#include <sample/public.hpp>
#include "internal.hpp"
namespace sample {
int add(int a, int b) { return internal::sub(a, -b); }
} // namespace sample
| 153 | 54 |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "EntityPanel.h"
#include "AIWavePanel.h"
#include "ShapePanel.h"
#include "Objects/EntityObject.h"
#include "Objects/ShapeObject.h"
#include "Objects/AIWave.h"
#include "StringDlg.h"
#include "CryEditDoc.h"
#include "Mission.h"
#include "MissionScript.h"
#include "EntityPrototype.h"
#include "QtViewPaneManager.h"
#include "GenericSelectItemDialog.h"
#include <HyperGraph/FlowGraphManager.h>
#include <HyperGraph/FlowGraph.h>
#include <HyperGraph/FlowGraphHelpers.h>
#include <HyperGraph/HyperGraphDialog.h>
#include <HyperGraph/FlowGraphSearchCtrl.h>
#include <TrackView/TrackViewDialog.h>
#include <ui_EntityPanel.h>
#include <ui_EntityEventsPanel.h>
#include "QtUtil.h"
#include <QInputDialog>
#include <QMenu>
#include <QTreeWidgetItem>
/////////////////////////////////////////////////////////////////////////////
// CEntityPanel dialog
CEntityPanel::CEntityPanel(QWidget* pParent /*=nullptr*/)
: QWidget(pParent)
, ui(new Ui::CEntityPanel)
{
m_entity = 0;
ui->setupUi(this);
m_editScriptButton = ui->EDITSCRIPT;
m_reloadScriptButton = ui->RELOADSCRIPT;
m_prototypeButton = ui->PROTOTYPE;
m_flowGraphOpenBtn = ui->OPENFLOWGRAPH;
m_flowGraphRemoveBtn = ui->REMOVEFLOWGRAPH;
m_flowGraphListBtn = ui->LIST_ENTITY_FLOWGRAPHS;
m_physicsBtn[0] = ui->GETPHYSICS;
m_physicsBtn[1] = ui->RESETPHYSICS;
m_trackViewSequenceButton = ui->TRACKVIEW_SEQUENCE;
m_frame = ui->FRAME2;
connect(m_editScriptButton, &QPushButton::clicked, this, &CEntityPanel::OnEditScript);
connect(m_reloadScriptButton, &QPushButton::clicked, this, &CEntityPanel::OnReloadScript);
connect(ui->FILE_COMMANDS, &QPushButton::clicked, this, &CEntityPanel::OnFileCommands);
connect(m_prototypeButton, &QPushButton::clicked, this, &CEntityPanel::OnPrototype);
connect(m_flowGraphOpenBtn, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedOpenFlowGraph);
connect(m_flowGraphRemoveBtn, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedRemoveFlowGraph);
connect(m_flowGraphListBtn, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedListFlowGraphs);
connect(m_physicsBtn[0], &QPushButton::clicked, this, &CEntityPanel::OnBnClickedGetphysics);
connect(m_physicsBtn[1], &QPushButton::clicked, this, &CEntityPanel::OnBnClickedResetphysics);
connect(m_trackViewSequenceButton, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedTrackViewSequence);
}
/////////////////////////////////////////////////////////////////////////////
// CEntityPanel message handlers
void CEntityPanel::SetEntity(CEntityObject* entity)
{
assert(entity);
m_entity = entity;
if (m_entity != NULL && m_entity->GetScript())
{
ui->SCRIPT_NAME->setText(m_entity->GetScript()->GetFile());
}
if (!qobject_cast<CAITerritoryObject*>(entity) && !qobject_cast<CAIWaveObject*>(entity))
{
if (qobject_cast<CAITerritoryPanel*>(this) || qobject_cast<CAIWavePanel*>(this))
{
return;
}
if (m_entity != NULL && !entity->GetPrototype())
{
m_prototypeButton->setEnabled(false);
m_prototypeButton->setText(tr("Entity Archetype"));
}
else
{
m_prototypeButton->setEnabled(true);
m_prototypeButton->setText(entity->GetPrototype()->GetFullName());
}
}
if (m_entity != NULL && m_entity->GetFlowGraph())
{
m_flowGraphOpenBtn->setText(tr("Open"));
m_flowGraphOpenBtn->setEnabled(true);
m_flowGraphRemoveBtn->setEnabled(true);
}
else
{
m_flowGraphOpenBtn->setText(tr("Create"));
m_flowGraphOpenBtn->setEnabled(true);
m_flowGraphRemoveBtn->setEnabled(false);
}
if (m_trackViewSequenceButton->isVisible())
{
CTrackViewAnimNode* pAnimNode = nullptr;
m_trackViewSequenceButton->setText(tr("Sequence"));
if (m_entity != nullptr && (pAnimNode = GetIEditor()->GetSequenceManager()->GetActiveAnimNode(entity)) && pAnimNode->GetSequence())
{
m_trackViewSequenceButton->setEnabled(true);
}
else
{
m_trackViewSequenceButton->setEnabled(false);
}
}
}
void CEntityPanel::OnEditScript()
{
assert(m_entity != 0);
CEntityScript* script = m_entity->GetScript();
AZStd::string cmd = AZStd::string::format("general.launch_lua_editor \'%s\'", script->GetFile().toUtf8().data());
GetIEditor()->ExecuteCommand(cmd.c_str());
}
void CEntityPanel::OnReloadScript()
{
assert(m_entity != 0);
m_entity->OnMenuReloadScripts();
}
void CEntityPanel::OnFileCommands()
{
assert(m_entity != 0);
CEntityScript* pScript = m_entity->GetScript();
if (pScript)
{
CFileUtil::PopupQMenu(Path::GetFile(pScript->GetFile()), Path::GetPath(pScript->GetFile()), this);
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityPanel::OnPrototype()
{
// Go to the entity prototype.
// Open corresponding prototype.
if (m_entity)
{
if (m_entity->GetPrototype())
{
GetIEditor()->OpenDataBaseLibrary(EDB_TYPE_ENTITY_ARCHETYPE, m_entity->GetPrototype());
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityPanel::OnBnClickedTrackViewSequence()
{
if (m_entity)
{
CTrackViewAnimNodeBundle bundle = GetIEditor()->GetSequenceManager()->GetAllRelatedAnimNodes(m_entity);
CTrackViewAnimNodeBundle finalBundle;
if (bundle.GetCount() > 0)
{
QMenu menu;
unsigned int id = 1;
for (unsigned int i = 0; i < bundle.GetCount(); ++i)
{
CTrackViewAnimNode* pNode = bundle.GetNode(i);
if (pNode->GetSequence())
{
menu.addAction(QtUtil::ToQString(pNode->GetSequence()->GetName()))->setData(id);
finalBundle.AppendAnimNode(pNode);
id++; // KDAB_PORT original code never incremented, so first one was always chosen. Right/Wrong?
}
}
QAction* res = menu.exec(QCursor::pos());
int chosen = res ? (res->data().toInt() - 1) : -1;
if (chosen >= 0)
{
QtViewPaneManager::instance()->OpenPane(LyViewPane::TrackView);
CTrackViewDialog* pTVDlg = CTrackViewDialog::GetCurrentInstance();
if (pTVDlg)
{
GetIEditor()->GetAnimation()->SetSequence(finalBundle.GetNode(chosen)->GetSequence(), false, false);
CTrackViewAnimNode* pNode = finalBundle.GetNode(chosen);
if (pNode)
{
pNode->SetSelected(true);
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityPanel::OnBnClickedGetphysics()
{
if (m_entity)
{
CUndo undo("Accept Physics State");
m_entity->AcceptPhysicsState();
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityPanel::OnBnClickedResetphysics()
{
if (m_entity)
{
CUndo undo("Reset Physics State");
m_entity->ResetPhysicsState();
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityPanel::OnBnClickedOpenFlowGraph()
{
if (m_entity)
{
if (!m_entity->GetFlowGraph())
{
m_entity->CreateFlowGraphWithGroupDialog();
}
else
{
// Flow graph already present.
m_entity->OpenFlowGraph("");
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityPanel::OnBnClickedRemoveFlowGraph()
{
if (m_entity)
{
if (m_entity->GetFlowGraph())
{
CUndo undo("Remove Flow graph");
QString str(tr("Remove Flow Graph for Entity %1?").arg(m_entity->GetName()));
if (QMessageBox::question(this, "Confirm", str, QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
{
m_entity->RemoveFlowGraph();
SetEntity(m_entity);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityPanel::OnBnClickedListFlowGraphs()
{
std::vector<CFlowGraph*> flowgraphs;
CFlowGraph* entityFG = 0;
FlowGraphHelpers::FindGraphsForEntity(m_entity, flowgraphs, entityFG);
if (flowgraphs.size() > 0)
{
QMenu menu;
unsigned int id = 1;
std::vector<CFlowGraph*>::const_iterator iter (flowgraphs.begin());
while (iter != flowgraphs.end())
{
QString name;
FlowGraphHelpers::GetHumanName(*iter, name);
if (*iter == entityFG)
{
name += " <GraphEntity>";
menu.addAction(name)->setData(id);
if (flowgraphs.size() > 1)
{
menu.addSeparator();
}
}
else
{
menu.addAction(name)->setData(id);
}
++id;
++iter;
}
QAction* res = menu.exec(QCursor::pos());
int chosen = res ? (res->data().toInt() - 1) : -1;
if (chosen >= 0)
{
GetIEditor()->GetFlowGraphManager()->OpenView(flowgraphs[chosen]);
CHyperGraphDialog* pHGDlg = CHyperGraphDialog::instance();
if (pHGDlg)
{
CFlowGraphSearchCtrl* pSC = pHGDlg->GetSearchControl();
if (pSC)
{
CFlowGraphSearchOptions* pOpts = CFlowGraphSearchOptions::GetSearchOptions();
pOpts->m_bIncludeEntities = true;
pOpts->m_findSpecial = CFlowGraphSearchOptions::eFLS_None;
pOpts->m_LookinIndex = CFlowGraphSearchOptions::eFL_Current;
pSC->Find(m_entity->GetName(), false, true, true);
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// CEntityEventsPanel dialog
CEntityEventsPanel::CEntityEventsPanel(QWidget* pParent /*=nullptr*/)
: QWidget(pParent)
, ui(new Ui::CEntityEventsPanel)
{
ui->setupUi(this);
m_entity = 0;
m_pickTool = 0;
m_sendEvent = ui->EVENT_SEND;
connect(m_sendEvent, &QPushButton::clicked, this, &CEntityEventsPanel::OnEventSend);
m_runButton = ui->RUN_METHOD;
connect(m_runButton, &QPushButton::clicked, this, &CEntityEventsPanel::OnRunMethod);
m_gotoMethodBtn = ui->GOTO_METHOD;
connect(m_gotoMethodBtn, &QPushButton::clicked, this, &CEntityEventsPanel::OnGotoMethod);
m_addMethodBtn = ui->ADD_METHOD;
connect(m_addMethodBtn, &QPushButton::clicked, this, &CEntityEventsPanel::OnAddMethod);
m_removeButton = ui->EVENT_REMOVE;
connect(m_removeButton, &QPushButton::clicked, this, &CEntityEventsPanel::OnEventRemove);
m_eventTree = ui->EVENTTREE;
m_eventTree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_eventTree, &QTreeWidget::customContextMenuRequested, this, &CEntityEventsPanel::OnRclickEventTree);
connect(m_eventTree, &QTreeWidget::itemDoubleClicked, this, &CEntityEventsPanel::OnDblClickEventTree);
connect(m_eventTree, &QTreeWidget::itemSelectionChanged, this, &CEntityEventsPanel::OnSelChangedEventTree);
m_pickButton = ui->EVENT_ADD;
//connect(m_pickButton, &QPushButton::clicked, this, &CEntityEventsPanel::OnEventAdd);
//m_pickButton.SetPickCallback(this, _T("Pick Target Entity for Event"), RUNTIME_CLASS(CEntityObject));
m_addMissionBtn = ui->EVENT_ADDMISSION;
connect(m_addMissionBtn, &QPushButton::clicked, this, &CEntityEventsPanel::OnBnAddMission);
m_methods = ui->METHODS;
connect(m_methods, &QListWidget::itemDoubleClicked, this, &CEntityEventsPanel::OnDblclkMethods);
connect(m_methods, &QListWidget::itemSelectionChanged, this, &CEntityEventsPanel::OnSelChangedMethods);
}
CEntityEventsPanel::~CEntityEventsPanel()
{
if (m_pickTool == GetIEditor()->GetEditTool())
{
GetIEditor()->SetEditTool(0);
}
m_pickTool = 0;
}
/////////////////////////////////////////////////////////////////////////////
// CEntityEventsPanel message handlers
void CEntityEventsPanel::SetEntity(CEntityObject* entity)
{
assert(entity);
m_entity = entity;
ReloadMethods();
ReloadEvents();
}
void CEntityEventsPanel::ReloadMethods()
{
assert(m_entity != 0);
// Parse entity lua file.
CEntityScript* script = m_entity->GetScript();
// Since method CEntityScriptDialog::SetScript, checks for script, we are checking here too.
if (!script)
{
return;
}
m_methods->clear();
///if (script->Load( m_entity->GetEntityClass() ))
{
for (int i = 0; i < script->GetMethodCount(); i++)
{
m_methods->addItem(script->GetMethod(i));
}
}
}
void CEntityEventsPanel::OnSelChangedMethods()
{
m_selectedMethod = m_methods->selectedItems().size() ? m_methods->selectedItems().front()->text() : QStringLiteral("");
}
void CEntityEventsPanel::OnDblclkMethods(QListWidgetItem* item)
{
GotoMethod(m_selectedMethod);
}
void CEntityEventsPanel::OnRunMethod()
{
assert(m_entity != 0);
CEntityScript* script = m_entity->GetScript();
if (m_entity->GetIEntity())
{
script->RunMethod(m_entity->GetIEntity(), m_selectedMethod);
}
}
void CEntityEventsPanel::GotoMethod(const QString& method)
{
assert(m_entity != 0);
CEntityScript* script = m_entity->GetScript();
script->GotoMethod(method);
}
void CEntityEventsPanel::OnGotoMethod()
{
GotoMethod(m_selectedMethod);
}
void CEntityEventsPanel::OnAddMethod()
{
assert(m_entity != 0);
bool ok;
QString method = QInputDialog::getText(this, tr("Add Method"), tr("Enter Method Name:"), QLineEdit::Normal, QStringLiteral(""), &ok);
if (ok && !method.isEmpty())
{
if (m_methods->findItems(method, Qt::MatchExactly).isEmpty())
{
CEntityScript* script = m_entity->GetScript();
script->AddMethod(method);
script->GotoMethod(method);
script->Reload();
m_entity->Reload(true);
}
}
}
void CEntityEventsPanel::ReloadEvents()
{
assert(m_entity != 0);
CEntityScript* script = m_entity->GetScript();
int i;
// Reload events tree.
m_eventTree->clear();
for (i = 0; i < script->GetEventCount(); i++)
{
QString sourceEvent = script->GetEvent(i);
QTreeWidgetItem* hRootItem = new QTreeWidgetItem();
hRootItem->setText(0, QString("On %1").arg(sourceEvent));
m_eventTree->addTopLevelItem(hRootItem);
bool haveEvents = false;
for (int j = 0; j < m_entity->GetEventTargetCount(); j++)
{
QString targetName;
CEntityEventTarget& et = m_entity->GetEventTarget(j);
if (sourceEvent.compare(et.sourceEvent, Qt::CaseInsensitive) != 0)
{
continue;
}
if (et.target)
{
targetName = et.target->GetName();
}
else
{
targetName = "Mission";
}
targetName += QString(" [%1]").arg(et.event);
QTreeWidgetItem* hEventItem = new QTreeWidgetItem(hRootItem);
hEventItem->setText(0, targetName);
hEventItem->setIcon(0, QIcon(":/Panels/EntityEventsPanel/res/icon_dot.png"));
hEventItem->setData(0, Qt::UserRole, j);
haveEvents = true;
}
if (haveEvents)
{
hRootItem->setExpanded(true);
QFont f = hRootItem->font(0);
f.setBold(true);
hRootItem->setFont(0, f);
}
}
m_pickButton->setEnabled(false);
m_removeButton->setEnabled(false);
m_sendEvent->setEnabled(false);
m_addMissionBtn->setEnabled(false);
m_currentTrgEventId = -1;
m_currentSourceEvent = "";
}
void CEntityEventsPanel::OnEventAdd()
{
// KDAB_PORT never called
assert(m_entity != 0);
//m_entity->PickEntity();
if (m_pickTool)
{
// If pick tool already enabled, disable it.
OnCancelPick();
}
GetIEditor()->PickObject(this, &CEntityObject::staticMetaObject, "Pick Target Entity for Event");
m_pickButton->setChecked(true);
}
//////////////////////////////////////////////////////////////////////////
void CEntityEventsPanel::OnEventRemove()
{
if (m_currentTrgEventId >= 0)
{
{
CUndo undo("Remove Event Target");
m_entity->RemoveEventTarget(m_currentTrgEventId);
}
ReloadEvents();
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityEventsPanel::OnBnAddMission()
{
assert(m_entity);
if (!m_currentSourceEvent.isEmpty())
{
CMissionScript* script = GetIEditor()->GetDocument()->GetCurrentMission()->GetScript();
if (!script)
{
return;
}
if (script->GetEventCount() < 1)
{
return;
}
// Popup Menu with Event selection.
QMenu menu;
for (int i = 0; i < script->GetEventCount(); i++)
{
menu.addAction(script->GetEvent(i))->setData(i + 1);
}
QAction* action = menu.exec(QCursor::pos());
int res = action ? action->data().toInt() : 0;
if (res > 0 && res < script->GetEventCount() + 1)
{
CUndo undo("Change Event");
QString event = script->GetEvent(res - 1);
m_entity->AddEventTarget(0, event, m_currentSourceEvent);
// Update script event table.
if (m_entity->GetScript())
{
m_entity->GetScript()->SetEventsTable(m_entity);
}
ReloadEvents();
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityEventsPanel::OnPick(CBaseObject* picked)
{
m_pickTool = 0;
CEntityObject* pickedEntity = (CEntityObject*)picked;
if (!pickedEntity)
{
return;
}
m_pickButton->setChecked(false);
if (pickedEntity->GetScript()->GetEventCount() > 0)
{
if (!m_currentSourceEvent.isEmpty())
{
CUndo undo("Add Event Target");
m_entity->AddEventTarget(pickedEntity, pickedEntity->GetScript()->GetEvent(0), m_currentSourceEvent);
if (m_entity->GetScript())
{
m_entity->GetScript()->SetEventsTable(m_entity);
}
ReloadEvents();
}
}
}
void CEntityEventsPanel::OnCancelPick()
{
m_pickButton->setChecked(false);
m_pickTool = 0;
}
void CEntityEventsPanel::OnSelChangedEventTree()
{
assert(m_entity != 0);
QTreeWidgetItem* selectedItem = m_eventTree->selectedItems().empty() ? nullptr : m_eventTree->selectedItems().front();
QString str;
if (selectedItem)
{
m_currentSourceEvent = selectedItem->text(0);
m_currentTrgEventId = -1;
//////////////////////////////////////////////////////////////////////////
// Timur: Old system disabled for now.
//////////////////////////////////////////////////////////////////////////
//m_pickButton->setEnabled(true);
m_removeButton->setEnabled(false);
m_sendEvent->setEnabled(true);
m_addMissionBtn->setEnabled(true);
if (selectedItem->data(0, Qt::UserRole).isValid())
{
int id = selectedItem->data(0, Qt::UserRole).toInt();
m_currentSourceEvent = m_entity->GetEventTarget(id).sourceEvent;
m_currentTrgEventId = id;
m_pickButton->setEnabled(false);
m_removeButton->setEnabled(true);
m_sendEvent->setEnabled(true);
m_addMissionBtn->setEnabled(false);
}
}
}
void CEntityEventsPanel::OnRclickEventTree()
{
// TODO: Add your control notification handler code here
if (m_currentTrgEventId >= 0)
{
CEntityScript* script = 0;
CMissionScript* missionScript = 0;
int eventCount = 0;
// Popup Menu with Event selection.
QMenu menu;
CBaseObject* trgObject = m_entity->GetEventTarget(m_currentTrgEventId).target;
if (trgObject != 0)
{
CEntityObject* targetEntity = (CEntityObject*)trgObject;
if (!targetEntity)
{
return;
}
script = targetEntity->GetScript();
if (!script)
{
return;
}
eventCount = script->GetEventCount();
for (int i = 0; i < eventCount; i++)
{
menu.addAction(script->GetEvent(i))->setData(i + 1);
}
}
else
{
missionScript = GetIEditor()->GetDocument()->GetCurrentMission()->GetScript();
if (!missionScript)
{
return;
}
eventCount = missionScript->GetEventCount();
for (int i = 0; i < eventCount; i++)
{
menu.addAction(missionScript->GetEvent(i))->setData(i + 1);
}
}
QAction* action = menu.exec(QCursor::pos());
int res = action ? action->data().toInt() : 0;
if (res > 0 && res < eventCount + 1)
{
CUndo undo("Change Event");
QString event;
if (script)
{
event = script->GetEvent(res - 1);
}
else if (missionScript)
{
event = missionScript->GetEvent(res - 1);
}
m_entity->GetEventTarget(m_currentTrgEventId).event = event;
// Update script event table.
if (m_entity->GetScript())
{
m_entity->GetScript()->SetEventsTable(m_entity);
}
ReloadEvents();
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityEventsPanel::OnDblClickEventTree()
{
/*
if (m_currentTrgEventId >= 0)
{
CBaseObject *trgObject = m_entity->GetEventTarget(m_currentTrgEventId).target;
if (trgObject != 0)
{
CUndo undo("Select Object" );
GetIEditor()->ClearSelection();
GetIEditor()->SelectObject( trgObject );
}
}*/
if (!m_currentSourceEvent.isEmpty())
{
CEntityScript* script = m_entity->GetScript();
if (m_entity->GetIEntity())
{
script->SendEvent(m_entity->GetIEntity(), m_currentSourceEvent);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityEventsPanel::OnEventSend()
{
if (!m_currentSourceEvent.isEmpty())
{
CEntityScript* script = m_entity->GetScript();
if (m_entity->GetIEntity())
{
script->SendEvent(m_entity->GetIEntity(), m_currentSourceEvent);
}
}
}
#include <EntityPanel.moc>
| 24,092 | 7,295 |