blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a019d8064a5a71f87d7618a710c39ba9e8568de7 | 847cccd728e768dc801d541a2d1169ef562311cd | /src/EntitySystem/Components/Script.h | 7d39f253e7f5fb6bc6e4fda92e16ca214e4b66f5 | [] | no_license | aadarshasubedi/Ocerus | 1bea105de9c78b741f3de445601f7dee07987b96 | 4920b99a89f52f991125c9ecfa7353925ea9603c | refs/heads/master | 2021-01-17T17:50:00.472657 | 2011-03-25T13:26:12 | 2011-03-25T13:26:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,634 | h | /// @file
/// Component for script calling
#ifndef Script_h__
#define Script_h__
#include "../ComponentMgr/Component.h"
namespace EntityComponents
{
/// This component allows entities to run scripts. It may run only scripts supported by ScriptSystem. The scripts are
/// executed as a reaction to received EntityMessage messages. For more informations about scripts see ScriptSystem.
class Script: public RTTIGlue<Script, Component>
{
public:
/// Called after the component is created.
virtual void Create(void);
/// Called before the component is destroyed.
virtual void Destroy(void);
/// Called when a new message arrives.
virtual EntityMessage::eResult HandleMessage(const EntityMessage& msg);
/// Called from RTTI when the component is allowed to set up its properties.
static void RegisterReflection(void);
/// Names of the script modules that are searched for script message handlers.
Utils::Array<ResourceSystem::ResourcePtr>* GetModules(void) const
{ return const_cast<Utils::Array<ResourceSystem::ResourcePtr>*>(&mModules); }
/// Names of the script modules that are searched for script message handlers.
void SetModules(Utils::Array<ResourceSystem::ResourcePtr>* modules);
/// Maximum number of miliseconds a script can run before it is terminated (0 means unlimited).
uint32 GetTimeOut(void) const { return mTimeOut; }
/// Maximum number of miliseconds a script can run before it is terminated (0 means unlimited).
void SetTimeOut(const uint32 timeOut) { mTimeOut = timeOut; }
/// States of OnAction handlers.
Utils::Array<int32>* GetStates(void) const { return const_cast<Utils::Array<int32>*>(&mStates); }
/// States of OnAction handlers.
void SetStates(Utils::Array<int32>* states) { mStates.CopyFrom(*states); }
/// Times of execution of OnAction handlers.
Utils::Array<uint64>* GetTimes(void) const { return const_cast<Utils::Array<uint64>*>(&mTimes); }
/// Times of execution of OnAction handlers.
void SetTimes(Utils::Array<uint64>* times) { mTimes.CopyFrom(*times); }
/// Current index of mStates and mTimes.
int32 GetCurrentArrayIndex(void) const { return mCurrentArrayIndex; }
/// This is called when the dynamic property was registered/unregistered.
virtual void DynamicPropertyChanged(const StringKey propertyName, bool reg, bool success);
private:
Utils::Array<ResourceSystem::ResourcePtr> mModules;
uint32 mTimeOut;
Utils::Array<int32> mStates;
Utils::Array<uint64> mTimes;
int32 mCurrentArrayIndex;
/// Whether the UpdateMessageHandlers() will be executed when next message in handled.
bool mNeedUpdate;
/// Whether the UpdateMessageHandlers() is being executed.
bool mIsUpdating;
/// Stores appropriate handler to message.
multimap<EntitySystem::EntityMessage::eType, int32> mMessageHandlers;
/// Map module name to function ID of OnAction handlers.
map<string, int32> mModuleToFuncID;
/// Map function ID of OnAction handlers to index of mStates and mTimes.
map<int32, int32> mFuncIDToArrayIndex;
/// Set of module names presented after the last call of UpdateMessageHandlers().
set<string> mOldModules;
/// Map module name to dynamic properties registered in the module.
map<string, set<StringKey> > mModuleDynamicProperties;
/// Find message handlers in modules (mModules) and store them to map (mMessageHandlers).
void UpdateMessageHandlers(void);
/// Execute a script function without parameters.
bool ExecuteScriptFunction(int32 funcId);
};
}
#endif | [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
10
],
[
14,
15
],
[
18,
18
],
[
21,
21
],
[
24,
25
],
[
27,
28
],
[
30,
31
],
[
34,
34
],
[
37,
37
],
[
40,
43
],
[
45,
49
],
[
51,
52
],
[
54,
55
],
[
57,
96
]
],
[
[
11,
13
],
[
16,
17
],
[
19,
20
],
[
22,
23
],
[
26,
26
],
[
29,
29
],
[
32,
33
],
[
35,
35
],
[
38,
38
],
[
44,
44
],
[
50,
50
],
[
53,
53
],
[
56,
56
]
],
[
[
36,
36
],
[
39,
39
]
]
] |
41bc08dfa58cfdaad28289d967abca5de38dfd92 | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/level/models/BoneHierarchy.h | 848dc81948b260a3b197bb15861d74ef62ca56ce | [] | no_license | galek/hesperus | 4eb10e05945c6134901cc677c991b74ce6c8ac1e | dabe7ce1bb65ac5aaad144933d0b395556c1adc4 | refs/heads/master | 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,057 | h | /***
* hesperus: BoneHierarchy.h
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#ifndef H_HESP_BONEHIERARCHY
#define H_HESP_BONEHIERARCHY
#include <map>
#include <vector>
#include "PoseModifier.h"
namespace hesp {
//#################### FORWARD DECLARATIONS ####################
typedef shared_ptr<class Bone> Bone_Ptr;
typedef shared_ptr<const class Bone> Bone_CPtr;
typedef shared_ptr<class ConfiguredPose> ConfiguredPose_Ptr;
typedef shared_ptr<const class Pose> Pose_CPtr;
typedef shared_ptr<const class RBTMatrix> RBTMatrix_CPtr;
//#################### TYPEDEFS ####################
typedef shared_ptr<class BoneHierarchy> BoneHierarchy_Ptr;
typedef shared_ptr<const class BoneHierarchy> BoneHierarchy_CPtr;
class BoneHierarchy
{
//#################### PRIVATE VARIABLES ####################
private:
std::vector<Bone_Ptr> m_bones;
std::map<std::string,int> m_boneLookup;
//#################### CONSTRUCTORS ####################
public:
explicit BoneHierarchy(const std::vector<Bone_Ptr>& bones);
//#################### PUBLIC METHODS ####################
public:
void attach_to_parent(const BoneHierarchy_Ptr& parent, const std::string& parentBoneName);
int bone_count() const;
Bone_Ptr bones(int i);
Bone_CPtr bones(int i) const;
Bone_Ptr bones(const std::string& name);
Bone_CPtr bones(const std::string& name) const;
ConfiguredPose_Ptr configure_pose(const Pose_CPtr& unconfiguredPose, const std::map<std::string,PoseModifier>& modifiers = std::map<std::string,PoseModifier>()) const;
void detach_from_parent();
int find_bone(const std::string& name) const;
//#################### PRIVATE METHODS ####################
private:
void calculate_absolute_matrices(const std::map<std::string,PoseModifier>& modifiers) const;
void calculate_absolute_matrix(const Bone_Ptr& bone, const std::map<std::string,PoseModifier>& modifiers) const;
void calculate_relative_matrices(const std::vector<RBTMatrix_CPtr>& unconfiguredRelMats) const;
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
59
]
]
] |
3040d877c995b7601f7b87983ea0888ec958aeb8 | eddd3b38e897eb6dcf311a3de1f33aa3f0d26b5c | /Sigleton.h | d3aac54e62a714f3ef92f7f1c7377c8de440d43b | [] | no_license | reyoung/tjufsmon | 41eb34979d885f479b7cc47d913df7c281090ce7 | 6a2f2000d41e59a00050b490ca1834da72183527 | refs/heads/master | 2020-11-26T21:14:04.139320 | 2010-11-24T14:18:31 | 2010-11-24T14:18:31 | 33,868,135 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 544 | h | /*
* File: Config..hxx
* Author: reyoung
*
* Created on 2010Äê2ÔÂ12ÈÕ, ÏÂÎç2:27
*/
#ifndef SIGLETON_H
#define SIGLETON_H
template <typename T>
/** \brief
* Impletment of sigleton design pattarn.
*/
class Sigleton
{
public:
/** \brief
* Singleton instance
* \return T&
*
*/
static T & instance()
{
static T m_instance;
return m_instance;
}
private:
Sigleton();
~Sigleton();
Sigleton(const Sigleton& other);
Sigleton operator = (const Sigleton& other);
};
#endif // SIGLETON_H
| [
"[email protected]@d1ef24bf-30e3-250a-0152-633f91453181"
] | [
[
[
1,
36
]
]
] |
ac0c5003a2132a4f3aa33224e3c889022eb9995c | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/interprocess/example/doc_bufferstream.cpp | 75d6c321c2020e5699c2e04c988a5d64cd307637 | [
"BSL-1.0"
] | permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,277 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2007. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
//[doc_bufferstream
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/streams/bufferstream.hpp>
#include <vector>
#include <iterator>
#include <cstddef>
//<-
#include "../test/get_process_id_name.hpp"
//->
using namespace boost::interprocess;
int main ()
{
//Remove shared memory on construction and destruction
struct shm_remove
{
//<-
#if 1
shm_remove() { shared_memory_object::remove(test::get_process_id_name()); }
~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); }
#else
//->
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
//<-
#endif
//->
} remover;
//Create shared memory
//<-
#if 1
managed_shared_memory segment(create_only,test::get_process_id_name(), 65536);
#else
//->
managed_shared_memory segment(create_only,
"MySharedMemory", //segment name
65536);
//<-
#endif
//->
//Fill data
std::vector<int> data;
data.reserve(100);
for(int i = 0; i < 100; ++i){
data.push_back(i);
}
const std::size_t BufferSize = 100*5;
//Allocate a buffer in shared memory to write data
char *my_cstring =
segment.construct<char>("MyCString")[BufferSize](0);
bufferstream mybufstream(my_cstring, BufferSize);
//Now write data to the buffer
for(int i = 0; i < 100; ++i){
mybufstream << data[i] << std::endl;
}
//Check there was no overflow attempt
assert(mybufstream.good());
//Extract all values from the shared memory string
//directly to a vector.
std::vector<int> data2;
std::istream_iterator<int> it(mybufstream), itend;
std::copy(it, itend, std::back_inserter(data2));
//This extraction should have ended will fail error since
//the numbers formatted in the buffer end before the end
//of the buffer. (Otherwise it would trigger eofbit)
assert(mybufstream.fail());
//Compare data
assert(std::equal(data.begin(), data.end(), data2.begin()));
//Clear errors and rewind
mybufstream.clear();
mybufstream.seekp(0, std::ios::beg);
//Now write again the data trying to do a buffer overflow
for(int i = 0, m = data.size()*5; i < m; ++i){
mybufstream << data[i%5] << std::endl;
}
//Now make sure badbit is active
//which means overflow attempt.
assert(!mybufstream.good());
assert(mybufstream.bad());
segment.destroy_ptr(my_cstring);
return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>
| [
"metrix@Blended.(none)"
] | [
[
[
1,
107
]
]
] |
f658ab7ab12812fcfc31239c64cddb15aa8df061 | 5d7d72f455eaa9fc01dce2d19bb6f849190cd0c5 | /Morphon/itkMorphonToolbooxFunction.h | 584137bf712e19bb76b1c095320d26994053c817 | [] | no_license | midas-journal/midas-journal-320 | 9a818fc8d99158c8b2f2ee98c808560c137f3a06 | 999dfa15ef4d0822c3216f6b40feddd4371d4ce9 | refs/heads/master | 2016-09-05T17:44:36.976789 | 2011-08-22T13:46:19 | 2011-08-22T13:46:19 | 2,248,624 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,430 | h | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkMorphonToolbooxFunction.h,v $
Language: C++
Date: $Date: 13th February 2009$
Version: $Revision: $
Copyright (c) 2009 Plumat Jerome, Benoit Macq
Laboratoire de Télécommunications et Télédétection
Ecole Polytechnique de Louvain
Université Catholique de Louvain
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef _itkMorphonToolbooxFunction_h_
#define _itkMorphonToolbooxFunction_h_
#include "itkFiniteDifferenceFunction.h"
namespace itk {
/** \class MorphonToolbooxFunction
*
* This is an abstract base class for all PDE functions which drives a
* deformable registration algorithm. It is used by
* PDEDeformationRegistrationFilter subclasses to compute the
* output deformation field which will map a moving image onto
* a fixed image.
*
* This class is used to stock a rescaled, but not defomed, moving image,
* this particular moving image type is used to produce the deformation field.
*
* This class is templated over the fixed image type, moving image type,
* certainty image type and the deformation field type.
*
* \sa MorphonToolbooxFunction
* \ingroup FiniteDifferenceFunctions
*/
template<class TFixedImage, class TMovingImage, class TDeformationField>
class ITK_EXPORT MorphonToolbooxFunction :
public FiniteDifferenceFunction<TDeformationField>
{
public:
/** Standard class typedefs. */
typedef MorphonToolbooxFunction Self;
typedef FiniteDifferenceFunction<TDeformationField> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Inherit some enums from the superclass. */
itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension);
/** Run-time type information (and related methods) */
itkTypeMacro( MorphonToolbooxFunction,
FiniteDifferenceFunction );
/** MovingImage image type. */
typedef TMovingImage MovingImageType;
typedef typename MovingImageType::ConstPointer MovingImagePointer;
/** FixedImage image type. */
typedef TFixedImage FixedImageType;
typedef typename FixedImageType::ConstPointer FixedImagePointer;
/** Deformation field type. */
typedef TDeformationField DeformationFieldType;
typedef typename DeformationFieldType::Pointer DeformationFieldTypePointer;
/** Set the moving image. */
void SetMovingImage( const MovingImageType * ptr )
{ m_MovingImage = ptr; }
/** Set the certainty image */
void SetCertaintyImage( MovingImageType * ptr )
{ m_CertaintyImage = ptr; }
/** Set the certainty image. */
void SetRescaledPrototype( MovingImageType * ptr )
{
m_RescaledPrototype = ptr;
}
/** Get the moving image. */
const MovingImageType * GetMovingImage(void) const
{ return m_MovingImage; }
/** Get the certainty image. */
MovingImageType * GetCertaintyImage(void) const
{ return m_CertaintyImage; }
/** Get the rescaled prototye. */
MovingImageType * GetRescaledPrototype(void) const
{
return m_RescaledPrototype ;
}
/** Set the fixed image. */
void SetFixedImage( const FixedImageType * ptr )
{ m_FixedImage = ptr; }
/** Get the fixed image. */
const FixedImageType * GetFixedImage(void) const
{ return m_FixedImage; }
/** Set the defromation field. */
void SetDeformationField( DeformationFieldTypePointer ptr )
{ m_DeformationField = ptr; }
/** Get the Deformation field. */
DeformationFieldTypePointer GetDeformationField(void)
{ return m_DeformationField; }
void SetEnergy( double e) { m_Energy=e;}
double GetEnergy( ) const { return m_Energy;}
void SetGradientStep( double e) { m_GradientStep = e;}
double GetGradientStep( ) const { return m_GradientStep ;}
void SetNormalizeGradient( bool e) { m_NormalizeGradient=e;}
bool GetNormalizeGradient( ) const { return m_NormalizeGradient;}
protected:
/** Default Constructor */
MorphonToolbooxFunction();
/** Default Destructor */
~MorphonToolbooxFunction() {}
void PrintSelf(std::ostream& os, Indent indent) const;
/** The moving image. */
MovingImagePointer m_MovingImage;
/** The fixed image. */
FixedImagePointer m_FixedImage;
/** The deformation field. */
DeformationFieldTypePointer m_DeformationField;
/** The certainly image. */
MovingImageType * m_CertaintyImage;
/** Rescaled Prototype */
MovingImageType * m_RescaledPrototype;
mutable double m_Energy;
bool m_NormalizeGradient;
mutable double m_GradientStep;
private:
MorphonToolbooxFunction(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMorphonToolbooxFunction.txx"
#endif
#endif
| [
"[email protected]"
] | [
[
[
1,
169
]
]
] |
13c127a9e671cdfe6c8beca0c9e32be3024ca1c1 | fc2f53c62ab435998421e2b26305e9fd963f79b3 | /src/AbstractPositionalLight.h | 4e475c44856b6d47740159cb879cffc13ad5b10a | [] | no_license | hrehfeld/ezrgraphicsdemo | 64446583c0d7ea4c89806be536ee02b76255a8b5 | 04e477f1fca28ee3c5216384e9757e75dda21f18 | refs/heads/master | 2020-05-18T00:44:54.669110 | 2009-07-13T18:31:03 | 2009-07-13T18:31:03 | 197,796 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 547 | h | #ifndef _ABSTRACTPOSITIONALLIGHT_H_
#define _ABSTRACTPOSITIONALLIGHT_H_
#include "Light.h"
#include <Eigen/Geometry>
namespace Ezr
{
class AbstractPositionalLight : public Light
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
virtual ~AbstractPositionalLight() = 0;
Eigen::Vector3f getPosition() const {return _position;}
protected:
AbstractPositionalLight(const Eigen::Vector3f& pos);
Eigen::Vector3f _position;
};
}
#endif /* _ABSTRACTPOSITIONALLIGHT_H_ */
| [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
642481e977b15a6ce9e9af5004883b2cf4993fe6 | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/threads/create_new_thread_extension.h | fe93a738a8eeeb73ca78713a9613595049355e51 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,179 | h | // Copyright (C) 2006 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_CREATE_NEW_THREAD_EXTENSIOn_
#define DLIB_CREATE_NEW_THREAD_EXTENSIOn_
#include "threads_kernel_abstract.h"
#include "create_new_thread_extension_abstract.h"
#include "../threads.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
template <
typename T,
void (T::*funct)()
>
inline void dlib_create_new_thread_helper (
void* obj
)
{
T* o = reinterpret_cast<T*>(obj);
(o->*funct)();
}
// ----------------------------------------------------------------------------------------
template <
typename T,
void (T::*funct)()
>
inline bool create_new_thread (
T& obj
)
{
return create_new_thread(dlib_create_new_thread_helper<T,funct>,&obj);
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_CREATE_NEW_THREAD_EXTENSIOn_
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
46
]
]
] |
084421247dfa3edbc196319e8a633e9b7b22cf9d | 83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c | /code/NFFLoader.cpp | a92e6218050265c849b9e1c7365bd2e13a3f5a7b | [
"BSD-3-Clause"
] | permissive | spring/assimp | fb53b91228843f7677fe8ec18b61d7b5886a6fd3 | db29c9a20d0dfa9f98c8fd473824bba5a895ae9e | refs/heads/master | 2021-01-17T23:19:56.511185 | 2011-11-08T12:15:18 | 2011-11-08T12:15:18 | 2,017,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 38,948 | cpp | /*
---------------------------------------------------------------------------
Open Asset Import Library (ASSIMP)
---------------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software 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 ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file Implementation of the STL importer class */
#include "AssimpPCH.h"
#ifndef ASSIMP_BUILD_NO_NFF_IMPORTER
// internal headers
#include "NFFLoader.h"
#include "ParsingUtils.h"
#include "StandardShapes.h"
#include "fast_atof.h"
#include "RemoveComments.h"
using namespace Assimp;
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
NFFImporter::NFFImporter()
{}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
NFFImporter::~NFFImporter()
{}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool NFFImporter::CanRead( const std::string& pFile, IOSystem* /*pIOHandler*/, bool /*checkSig*/) const
{
return SimpleExtensionCheck(pFile,"nff","enff");
}
// ------------------------------------------------------------------------------------------------
// Get the list of all supported file extensions
void NFFImporter::GetExtensionList(std::set<std::string>& extensions)
{
extensions.insert("enff");
extensions.insert("nff");
}
// ------------------------------------------------------------------------------------------------
#define AI_NFF_PARSE_FLOAT(f) \
SkipSpaces(&sz); \
if (!::IsLineEnd(*sz))sz = fast_atof_move(sz, (float&)f);
// ------------------------------------------------------------------------------------------------
#define AI_NFF_PARSE_TRIPLE(v) \
AI_NFF_PARSE_FLOAT(v[0]) \
AI_NFF_PARSE_FLOAT(v[1]) \
AI_NFF_PARSE_FLOAT(v[2])
// ------------------------------------------------------------------------------------------------
#define AI_NFF_PARSE_SHAPE_INFORMATION() \
aiVector3D center, radius(1.0f,get_qnan(),get_qnan()); \
AI_NFF_PARSE_TRIPLE(center); \
AI_NFF_PARSE_TRIPLE(radius); \
if (is_qnan(radius.z))radius.z = radius.x; \
if (is_qnan(radius.y))radius.y = radius.x; \
currentMesh.radius = radius; \
currentMesh.center = center;
// ------------------------------------------------------------------------------------------------
#define AI_NFF2_GET_NEXT_TOKEN() \
do \
{ \
if (!GetNextLine(buffer,line)) \
{DefaultLogger::get()->warn("NFF2: Unexpected EOF, can't read next token");break;} \
SkipSpaces(line,&sz); \
} \
while(IsLineEnd(*sz))
// ------------------------------------------------------------------------------------------------
// Loads the materail table for the NFF2 file format from an external file
void NFFImporter::LoadNFF2MaterialTable(std::vector<ShadingInfo>& output,
const std::string& path, IOSystem* pIOHandler)
{
boost::scoped_ptr<IOStream> file( pIOHandler->Open( path, "rb"));
// Check whether we can read from the file
if( !file.get()) {
DefaultLogger::get()->error("NFF2: Unable to open material library " + path + ".");
return;
}
// get the size of the file
const unsigned int m = (unsigned int)file->FileSize();
// allocate storage and copy the contents of the file to a memory buffer
// (terminate it with zero)
std::vector<char> mBuffer2(m+1);
TextFileToBuffer(file.get(),mBuffer2);
const char* buffer = &mBuffer2[0];
// First of all: remove all comments from the file
CommentRemover::RemoveLineComments("//",&mBuffer2[0]);
// The file should start with the magic sequence "mat"
if (!TokenMatch(buffer,"mat",3)) {
DefaultLogger::get()->error("NFF2: Not a valid material library " + path + ".");
return;
}
ShadingInfo* curShader = NULL;
// No read the file line per line
char line[4096];
const char* sz;
while (GetNextLine(buffer,line))
{
SkipSpaces(line,&sz);
// 'version' defines the version of the file format
if (TokenMatch(sz,"version",7))
{
DefaultLogger::get()->info("NFF (Sense8) material library file format: " + std::string(sz));
}
// 'matdef' starts a new material in the file
else if (TokenMatch(sz,"matdef",6))
{
// add a new material to the list
output.push_back( ShadingInfo() );
curShader = & output.back();
// parse the name of the material
}
else if (!TokenMatch(sz,"valid",5))
{
// check whether we have an active material at the moment
if (!IsLineEnd(*sz))
{
if (!curShader)
{
DefaultLogger::get()->error(std::string("NFF2 material library: Found element ") +
sz + "but there is no active material");
continue;
}
}
else continue;
// now read the material property and determine its type
aiColor3D c;
if (TokenMatch(sz,"ambient",7))
{
AI_NFF_PARSE_TRIPLE(c);
curShader->ambient = c;
}
else if (TokenMatch(sz,"diffuse",7) || TokenMatch(sz,"ambientdiffuse",14) /* correct? */)
{
AI_NFF_PARSE_TRIPLE(c);
curShader->diffuse = curShader->ambient = c;
}
else if (TokenMatch(sz,"specular",8))
{
AI_NFF_PARSE_TRIPLE(c);
curShader->specular = c;
}
else if (TokenMatch(sz,"emission",8))
{
AI_NFF_PARSE_TRIPLE(c);
curShader->emissive = c;
}
else if (TokenMatch(sz,"shininess",9))
{
AI_NFF_PARSE_FLOAT(curShader->shininess);
}
else if (TokenMatch(sz,"opacity",7))
{
AI_NFF_PARSE_FLOAT(curShader->opacity);
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void NFFImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler)
{
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
// Check whether we can read from the file
if( !file.get())
throw DeadlyImportError( "Failed to open NFF file " + pFile + ".");
unsigned int m = (unsigned int)file->FileSize();
// allocate storage and copy the contents of the file to a memory buffer
// (terminate it with zero)
std::vector<char> mBuffer2;
TextFileToBuffer(file.get(),mBuffer2);
const char* buffer = &mBuffer2[0];
// mesh arrays - separate here to make the handling of the pointers below easier.
std::vector<MeshInfo> meshes;
std::vector<MeshInfo> meshesWithNormals;
std::vector<MeshInfo> meshesWithUVCoords;
std::vector<MeshInfo> meshesLocked;
char line[4096];
const char* sz;
// camera parameters
aiVector3D camPos, camUp(0.f,1.f,0.f), camLookAt(0.f,0.f,1.f);
float angle = 45.f;
aiVector2D resolution;
bool hasCam = false;
MeshInfo* currentMeshWithNormals = NULL;
MeshInfo* currentMesh = NULL;
MeshInfo* currentMeshWithUVCoords = NULL;
ShadingInfo s; // current material info
// degree of tesselation
unsigned int iTesselation = 4;
// some temporary variables we need to parse the file
unsigned int sphere = 0,
cylinder = 0,
cone = 0,
numNamed = 0,
dodecahedron = 0,
octahedron = 0,
tetrahedron = 0,
hexahedron = 0;
// lights imported from the file
std::vector<Light> lights;
// check whether this is the NFF2 file format
if (TokenMatch(buffer,"nff",3))
{
const float qnan = get_qnan();
const aiColor4D cQNAN = aiColor4D (qnan,0.f,0.f,1.f);
const aiVector3D vQNAN = aiVector3D(qnan,0.f,0.f);
// another NFF file format ... just a raw parser has been implemented
// no support for further details, I don't think it is worth the effort
// http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/nff/nff2.html
// http://www.netghost.narod.ru/gff/graphics/summary/sense8.htm
// First of all: remove all comments from the file
CommentRemover::RemoveLineComments("//",&mBuffer2[0]);
while (GetNextLine(buffer,line))
{
SkipSpaces(line,&sz);
if (TokenMatch(sz,"version",7))
{
DefaultLogger::get()->info("NFF (Sense8) file format: " + std::string(sz));
}
else if (TokenMatch(sz,"viewpos",7))
{
AI_NFF_PARSE_TRIPLE(camPos);
hasCam = true;
}
else if (TokenMatch(sz,"viewdir",7))
{
AI_NFF_PARSE_TRIPLE(camLookAt);
hasCam = true;
}
// This starts a new object section
else if (!IsSpaceOrNewLine(*sz))
{
unsigned int subMeshIdx = 0;
// read the name of the object, skip all spaces
// at the end of it.
const char* sz3 = sz;
while (!IsSpaceOrNewLine(*sz))++sz;
std::string objectName = std::string(sz3,(unsigned int)(sz-sz3));
const unsigned int objStart = (unsigned int)meshes.size();
// There could be a material table in a separate file
std::vector<ShadingInfo> materialTable;
while (true)
{
AI_NFF2_GET_NEXT_TOKEN();
// material table - an external file
if (TokenMatch(sz,"mtable",6))
{
SkipSpaces(&sz);
sz3 = sz;
while (!IsSpaceOrNewLine(*sz))++sz;
const unsigned int diff = (unsigned int)(sz-sz3);
if (!diff)DefaultLogger::get()->warn("NFF2: Found empty mtable token");
else
{
// The material table has the file extension .mat.
// If it is not there, we need to append it
std::string path = std::string(sz3,diff);
if(std::string::npos == path.find_last_of(".mat"))
{
path.append(".mat");
}
// Now extract the working directory from the path to
// this file and append the material library filename
// to it.
std::string::size_type s;
if ((std::string::npos == (s = path.find_last_of('\\')) || !s) &&
(std::string::npos == (s = path.find_last_of('/')) || !s) )
{
s = pFile.find_last_of('\\');
if (std::string::npos == s)s = pFile.find_last_of('/');
if (std::string::npos != s)
{
path = pFile.substr(0,s+1) + path;
}
}
LoadNFF2MaterialTable(materialTable,path,pIOHandler);
}
}
else break;
}
// read the numbr of vertices
unsigned int num = ::strtoul10(sz,&sz);
// temporary storage
std::vector<aiColor4D> tempColors;
std::vector<aiVector3D> tempPositions,tempTextureCoords,tempNormals;
bool hasNormals = false,hasUVs = false,hasColor = false;
tempPositions.reserve (num);
tempColors.reserve (num);
tempNormals.reserve (num);
tempTextureCoords.reserve (num);
for (unsigned int i = 0; i < num; ++i)
{
AI_NFF2_GET_NEXT_TOKEN();
aiVector3D v;
AI_NFF_PARSE_TRIPLE(v);
tempPositions.push_back(v);
// parse all other attributes in the line
while (true)
{
SkipSpaces(&sz);
if (IsLineEnd(*sz))break;
// color definition
if (TokenMatch(sz,"0x",2))
{
hasColor = true;
register unsigned int numIdx = ::strtoul16(sz,&sz);
aiColor4D clr;
clr.a = 1.f;
// 0xRRGGBB
clr.r = ((numIdx >> 16u) & 0xff) / 255.f;
clr.g = ((numIdx >> 8u) & 0xff) / 255.f;
clr.b = ((numIdx) & 0xff) / 255.f;
tempColors.push_back(clr);
}
// normal vector
else if (TokenMatch(sz,"norm",4))
{
hasNormals = true;
AI_NFF_PARSE_TRIPLE(v);
tempNormals.push_back(v);
}
// UV coordinate
else if (TokenMatch(sz,"uv",2))
{
hasUVs = true;
AI_NFF_PARSE_FLOAT(v.x);
AI_NFF_PARSE_FLOAT(v.y);
v.z = 0.f;
tempTextureCoords.push_back(v);
}
}
// fill in dummies for all attributes that have not been set
if (tempNormals.size() != tempPositions.size())
tempNormals.push_back(vQNAN);
if (tempTextureCoords.size() != tempPositions.size())
tempTextureCoords.push_back(vQNAN);
if (tempColors.size() != tempPositions.size())
tempColors.push_back(cQNAN);
}
AI_NFF2_GET_NEXT_TOKEN();
if (!num)throw DeadlyImportError("NFF2: There are zero vertices");
num = ::strtoul10(sz,&sz);
std::vector<unsigned int> tempIdx;
tempIdx.reserve(10);
for (unsigned int i = 0; i < num; ++i)
{
AI_NFF2_GET_NEXT_TOKEN();
SkipSpaces(line,&sz);
unsigned int numIdx = ::strtoul10(sz,&sz);
// read all faces indices
if (numIdx)
{
// mesh.faces.push_back(numIdx);
// tempIdx.erase(tempIdx.begin(),tempIdx.end());
tempIdx.resize(numIdx);
for (unsigned int a = 0; a < numIdx;++a)
{
SkipSpaces(sz,&sz);
m = ::strtoul10(sz,&sz);
if (m >= (unsigned int)tempPositions.size())
{
DefaultLogger::get()->error("NFF2: Vertex index overflow");
m= 0;
}
// mesh.vertices.push_back (tempPositions[idx]);
tempIdx[a] = m;
}
}
// build a temporary shader object for the face.
ShadingInfo shader;
unsigned int matIdx = 0;
// white material color - we have vertex colors
shader.color = aiColor3D(1.f,1.f,1.f);
aiColor4D c = aiColor4D(1.f,1.f,1.f,1.f);
while (true)
{
SkipSpaces(sz,&sz);
if(IsLineEnd(*sz))break;
// per-polygon colors
if (TokenMatch(sz,"0x",2))
{
hasColor = true;
const char* sz2 = sz;
numIdx = ::strtoul16(sz,&sz);
const unsigned int diff = (unsigned int)(sz-sz2);
// 0xRRGGBB
if (diff > 3)
{
c.r = ((numIdx >> 16u) & 0xff) / 255.f;
c.g = ((numIdx >> 8u) & 0xff) / 255.f;
c.b = ((numIdx) & 0xff) / 255.f;
}
// 0xRGB
else
{
c.r = ((numIdx >> 8u) & 0xf) / 16.f;
c.g = ((numIdx >> 4u) & 0xf) / 16.f;
c.b = ((numIdx) & 0xf) / 16.f;
}
}
// TODO - implement texture mapping here
#if 0
// mirror vertex texture coordinate?
else if (TokenMatch(sz,"mirror",6))
{
}
// texture coordinate scaling
else if (TokenMatch(sz,"scale",5))
{
}
// texture coordinate translation
else if (TokenMatch(sz,"trans",5))
{
}
// texture coordinate rotation angle
else if (TokenMatch(sz,"rot",3))
{
}
#endif
// texture file name for this polygon + mapping information
else if ('_' == sz[0])
{
// get mapping information
switch (sz[1])
{
case 'v':
case 'V':
shader.shaded = false;
break;
case 't':
case 'T':
case 'u':
case 'U':
DefaultLogger::get()->warn("Unsupported NFF2 texture attribute: trans");
};
if (!sz[1] || '_' != sz[2])
{
DefaultLogger::get()->warn("NFF2: Expected underscore after texture attributes");
continue;
}
const char* sz2 = sz+3;
while (!IsSpaceOrNewLine( *sz ))++sz;
const unsigned int diff = (unsigned int)(sz-sz2);
if (diff)shader.texFile = std::string(sz2,diff);
}
// Two-sided material?
else if (TokenMatch(sz,"both",4))
{
shader.twoSided = true;
}
// Material ID?
else if (!materialTable.empty() && TokenMatch(sz,"matid",5))
{
SkipSpaces(&sz);
matIdx = ::strtoul10(sz,&sz);
if (matIdx >= materialTable.size())
{
DefaultLogger::get()->error("NFF2: Material index overflow.");
matIdx = 0;
}
// now combine our current shader with the shader we
// read from the material table.
ShadingInfo& mat = materialTable[matIdx];
shader.ambient = mat.ambient;
shader.diffuse = mat.diffuse;
shader.emissive = mat.emissive;
shader.opacity = mat.opacity;
shader.specular = mat.specular;
shader.shininess = mat.shininess;
}
else SkipToken(sz);
}
// search the list of all shaders we have for this object whether
// there is an identical one. In this case, we append our mesh
// data to it.
MeshInfo* mesh = NULL;
for (std::vector<MeshInfo>::iterator it = meshes.begin() + objStart, end = meshes.end();
it != end; ++it)
{
if ((*it).shader == shader && (*it).matIndex == matIdx)
{
// we have one, we can append our data to it
mesh = &(*it);
}
}
if (!mesh)
{
meshes.push_back(MeshInfo(PatchType_Simple,false));
mesh = &meshes.back();
mesh->matIndex = matIdx;
// We need to add a new mesh to the list. We assign
// an unique name to it to make sure the scene will
// pass the validation step for the moment.
// TODO: fix naming of objects in the scenegraph later
if (objectName.length())
{
::strcpy(mesh->name,objectName.c_str());
ASSIMP_itoa10(&mesh->name[objectName.length()],30,subMeshIdx++);
}
// copy the shader to the mesh.
mesh->shader = shader;
}
// fill the mesh with data
if (!tempIdx.empty())
{
mesh->faces.push_back((unsigned int)tempIdx.size());
for (std::vector<unsigned int>::const_iterator it = tempIdx.begin(), end = tempIdx.end();
it != end;++it)
{
m = *it;
// copy colors -vertex color specifications override polygon color specifications
if (hasColor)
{
const aiColor4D& clr = tempColors[m];
mesh->colors.push_back((is_qnan( clr.r ) ? c : clr));
}
// positions should always be there
mesh->vertices.push_back (tempPositions[m]);
// copy normal vectors
if (hasNormals)
mesh->normals.push_back (tempNormals[m]);
// copy texture coordinates
if (hasUVs)
mesh->uvs.push_back (tempTextureCoords[m]);
}
}
}
if (!num)throw DeadlyImportError("NFF2: There are zero faces");
}
}
camLookAt = camLookAt + camPos;
}
else // "Normal" Neutral file format that is quite more common
{
while (GetNextLine(buffer,line))
{
sz = line;
if ('p' == line[0] || TokenMatch(sz,"tpp",3))
{
MeshInfo* out = NULL;
// 'tpp' - texture polygon patch primitive
if ('t' == line[0])
{
currentMeshWithUVCoords = NULL;
for (std::vector<MeshInfo>::iterator it = meshesWithUVCoords.begin(), end = meshesWithUVCoords.end();
it != end;++it)
{
if ((*it).shader == s)
{
currentMeshWithUVCoords = &(*it);
break;
}
}
if (!currentMeshWithUVCoords)
{
meshesWithUVCoords.push_back(MeshInfo(PatchType_UVAndNormals));
currentMeshWithUVCoords = &meshesWithUVCoords.back();
currentMeshWithUVCoords->shader = s;
}
out = currentMeshWithUVCoords;
}
// 'pp' - polygon patch primitive
else if ('p' == line[1])
{
currentMeshWithNormals = NULL;
for (std::vector<MeshInfo>::iterator it = meshesWithNormals.begin(), end = meshesWithNormals.end();
it != end;++it)
{
if ((*it).shader == s)
{
currentMeshWithNormals = &(*it);
break;
}
}
if (!currentMeshWithNormals)
{
meshesWithNormals.push_back(MeshInfo(PatchType_Normals));
currentMeshWithNormals = &meshesWithNormals.back();
currentMeshWithNormals->shader = s;
}
sz = &line[2];out = currentMeshWithNormals;
}
// 'p' - polygon primitive
else
{
currentMesh = NULL;
for (std::vector<MeshInfo>::iterator it = meshes.begin(), end = meshes.end();
it != end;++it)
{
if ((*it).shader == s)
{
currentMesh = &(*it);
break;
}
}
if (!currentMesh)
{
meshes.push_back(MeshInfo(PatchType_Simple));
currentMesh = &meshes.back();
currentMesh->shader = s;
}
sz = &line[1];out = currentMesh;
}
SkipSpaces(sz,&sz);
m = strtoul10(sz);
// ---- flip the face order
out->vertices.resize(out->vertices.size()+m);
if (out != currentMesh)
{
out->normals.resize(out->vertices.size());
}
if (out == currentMeshWithUVCoords)
{
out->uvs.resize(out->vertices.size());
}
for (unsigned int n = 0; n < m;++n)
{
if(!GetNextLine(buffer,line))
{
DefaultLogger::get()->error("NFF: Unexpected EOF was encountered. Patch definition incomplete");
continue;
}
aiVector3D v; sz = &line[0];
AI_NFF_PARSE_TRIPLE(v);
out->vertices[out->vertices.size()-n-1] = v;
if (out != currentMesh)
{
AI_NFF_PARSE_TRIPLE(v);
out->normals[out->vertices.size()-n-1] = v;
}
if (out == currentMeshWithUVCoords)
{
// FIX: in one test file this wraps over multiple lines
SkipSpaces(&sz);
if (IsLineEnd(*sz))
{
GetNextLine(buffer,line);
sz = line;
}
AI_NFF_PARSE_FLOAT(v.x);
SkipSpaces(&sz);
if (IsLineEnd(*sz))
{
GetNextLine(buffer,line);
sz = line;
}
AI_NFF_PARSE_FLOAT(v.y);
v.y = 1.f - v.y;
out->uvs[out->vertices.size()-n-1] = v;
}
}
out->faces.push_back(m);
}
// 'f' - shading information block
else if (TokenMatch(sz,"f",1))
{
float d;
// read the RGB colors
AI_NFF_PARSE_TRIPLE(s.color);
// read the other properties
AI_NFF_PARSE_FLOAT(s.diffuse.r);
AI_NFF_PARSE_FLOAT(s.specular.r);
AI_NFF_PARSE_FLOAT(d); // skip shininess and transmittance
AI_NFF_PARSE_FLOAT(d);
AI_NFF_PARSE_FLOAT(s.refracti);
// NFF2 uses full colors here so we need to use them too
// although NFF uses simple scaling factors
s.diffuse.g = s.diffuse.b = s.diffuse.r;
s.specular.g = s.specular.b = s.specular.r;
// if the next one is NOT a number we assume it is a texture file name
// this feature is used by some NFF files on the internet and it has
// been implemented as it can be really useful
SkipSpaces(&sz);
if (!IsNumeric(*sz))
{
// TODO: Support full file names with spaces and quotation marks ...
const char* p = sz;
while (!IsSpaceOrNewLine( *sz ))++sz;
unsigned int diff = (unsigned int)(sz-p);
if (diff)
{
s.texFile = std::string(p,diff);
}
}
else
{
AI_NFF_PARSE_FLOAT(s.ambient); // optional
}
}
// 'shader' - other way to specify a texture
else if (TokenMatch(sz,"shader",6))
{
SkipSpaces(&sz);
const char* old = sz;
while (!IsSpaceOrNewLine(*sz))++sz;
s.texFile = std::string(old, (uintptr_t)sz - (uintptr_t)old);
}
// 'l' - light source
else if (TokenMatch(sz,"l",1))
{
lights.push_back(Light());
Light& light = lights.back();
AI_NFF_PARSE_TRIPLE(light.position);
AI_NFF_PARSE_FLOAT (light.intensity);
AI_NFF_PARSE_TRIPLE(light.color);
}
// 's' - sphere
else if (TokenMatch(sz,"s",1))
{
meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
MeshInfo& currentMesh = meshesLocked.back();
currentMesh.shader = s;
currentMesh.shader.mapping = aiTextureMapping_SPHERE;
AI_NFF_PARSE_SHAPE_INFORMATION();
// we don't need scaling or translation here - we do it in the node's transform
StandardShapes::MakeSphere(iTesselation, currentMesh.vertices);
currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
// generate a name for the mesh
::sprintf(currentMesh.name,"sphere_%i",sphere++);
}
// 'dod' - dodecahedron
else if (TokenMatch(sz,"dod",3))
{
meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
MeshInfo& currentMesh = meshesLocked.back();
currentMesh.shader = s;
currentMesh.shader.mapping = aiTextureMapping_SPHERE;
AI_NFF_PARSE_SHAPE_INFORMATION();
// we don't need scaling or translation here - we do it in the node's transform
StandardShapes::MakeDodecahedron(currentMesh.vertices);
currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
// generate a name for the mesh
::sprintf(currentMesh.name,"dodecahedron_%i",dodecahedron++);
}
// 'oct' - octahedron
else if (TokenMatch(sz,"oct",3))
{
meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
MeshInfo& currentMesh = meshesLocked.back();
currentMesh.shader = s;
currentMesh.shader.mapping = aiTextureMapping_SPHERE;
AI_NFF_PARSE_SHAPE_INFORMATION();
// we don't need scaling or translation here - we do it in the node's transform
StandardShapes::MakeOctahedron(currentMesh.vertices);
currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
// generate a name for the mesh
::sprintf(currentMesh.name,"octahedron_%i",octahedron++);
}
// 'tet' - tetrahedron
else if (TokenMatch(sz,"tet",3))
{
meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
MeshInfo& currentMesh = meshesLocked.back();
currentMesh.shader = s;
currentMesh.shader.mapping = aiTextureMapping_SPHERE;
AI_NFF_PARSE_SHAPE_INFORMATION();
// we don't need scaling or translation here - we do it in the node's transform
StandardShapes::MakeTetrahedron(currentMesh.vertices);
currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
// generate a name for the mesh
::sprintf(currentMesh.name,"tetrahedron_%i",tetrahedron++);
}
// 'hex' - hexahedron
else if (TokenMatch(sz,"hex",3))
{
meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
MeshInfo& currentMesh = meshesLocked.back();
currentMesh.shader = s;
currentMesh.shader.mapping = aiTextureMapping_BOX;
AI_NFF_PARSE_SHAPE_INFORMATION();
// we don't need scaling or translation here - we do it in the node's transform
StandardShapes::MakeHexahedron(currentMesh.vertices);
currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
// generate a name for the mesh
::sprintf(currentMesh.name,"hexahedron_%i",hexahedron++);
}
// 'c' - cone
else if (TokenMatch(sz,"c",1))
{
meshesLocked.push_back(MeshInfo(PatchType_Simple,true));
MeshInfo& currentMesh = meshesLocked.back();
currentMesh.shader = s;
currentMesh.shader.mapping = aiTextureMapping_CYLINDER;
if(!GetNextLine(buffer,line))
{
DefaultLogger::get()->error("NFF: Unexpected end of file (cone definition not complete)");
break;
}
sz = line;
// read the two center points and the respective radii
aiVector3D center1, center2; float radius1, radius2;
AI_NFF_PARSE_TRIPLE(center1);
AI_NFF_PARSE_FLOAT(radius1);
if(!GetNextLine(buffer,line))
{
DefaultLogger::get()->error("NFF: Unexpected end of file (cone definition not complete)");
break;
}
sz = line;
AI_NFF_PARSE_TRIPLE(center2);
AI_NFF_PARSE_FLOAT(radius2);
// compute the center point of the cone/cylinder -
// it is its local transformation origin
currentMesh.dir = center2-center1;
currentMesh.center = center1+currentMesh.dir/2.f;
float f;
if (( f = currentMesh.dir.Length()) < 10e-3f )
{
DefaultLogger::get()->error("NFF: Cone height is close to zero");
continue;
}
currentMesh.dir /= f; // normalize
// generate the cone - it consists of simple triangles
StandardShapes::MakeCone(f, radius1, radius2,
integer_pow(4, iTesselation), currentMesh.vertices);
// MakeCone() returns tris
currentMesh.faces.resize(currentMesh.vertices.size()/3,3);
// generate a name for the mesh. 'cone' if it a cone,
// 'cylinder' if it is a cylinder. Funny, isn't it?
if (radius1 != radius2)
::sprintf(currentMesh.name,"cone_%i",cone++);
else ::sprintf(currentMesh.name,"cylinder_%i",cylinder++);
}
// 'tess' - tesselation
else if (TokenMatch(sz,"tess",4))
{
SkipSpaces(&sz);
iTesselation = strtoul10(sz);
}
// 'from' - camera position
else if (TokenMatch(sz,"from",4))
{
AI_NFF_PARSE_TRIPLE(camPos);
hasCam = true;
}
// 'at' - camera look-at vector
else if (TokenMatch(sz,"at",2))
{
AI_NFF_PARSE_TRIPLE(camLookAt);
hasCam = true;
}
// 'up' - camera up vector
else if (TokenMatch(sz,"up",2))
{
AI_NFF_PARSE_TRIPLE(camUp);
hasCam = true;
}
// 'angle' - (half?) camera field of view
else if (TokenMatch(sz,"angle",5))
{
AI_NFF_PARSE_FLOAT(angle);
hasCam = true;
}
// 'resolution' - used to compute the screen aspect
else if (TokenMatch(sz,"resolution",10))
{
AI_NFF_PARSE_FLOAT(resolution.x);
AI_NFF_PARSE_FLOAT(resolution.y);
hasCam = true;
}
// 'pb' - bezier patch. Not supported yet
else if (TokenMatch(sz,"pb",2))
{
DefaultLogger::get()->error("NFF: Encountered unsupported ID: bezier patch");
}
// 'pn' - NURBS. Not supported yet
else if (TokenMatch(sz,"pn",2) || TokenMatch(sz,"pnn",3))
{
DefaultLogger::get()->error("NFF: Encountered unsupported ID: NURBS");
}
// '' - comment
else if ('#' == line[0])
{
const char* sz;SkipSpaces(&line[1],&sz);
if (!IsLineEnd(*sz))DefaultLogger::get()->info(sz);
}
}
}
// copy all arrays into one large
meshes.reserve (meshes.size()+meshesLocked.size()+meshesWithNormals.size()+meshesWithUVCoords.size());
meshes.insert (meshes.end(),meshesLocked.begin(),meshesLocked.end());
meshes.insert (meshes.end(),meshesWithNormals.begin(),meshesWithNormals.end());
meshes.insert (meshes.end(),meshesWithUVCoords.begin(),meshesWithUVCoords.end());
// now generate output meshes. first find out how many meshes we'll need
std::vector<MeshInfo>::const_iterator it = meshes.begin(), end = meshes.end();
for (;it != end;++it)
{
if (!(*it).faces.empty())
{
++pScene->mNumMeshes;
if ((*it).name[0])++numNamed;
}
}
// generate a dummy root node - assign all unnamed elements such
// as polygons and polygon patches to the root node and generate
// sub nodes for named objects such as spheres and cones.
aiNode* const root = new aiNode();
root->mName.Set("<NFF_Root>");
root->mNumChildren = numNamed + (hasCam ? 1 : 0) + (unsigned int) lights.size();
root->mNumMeshes = pScene->mNumMeshes-numNamed;
aiNode** ppcChildren = NULL;
unsigned int* pMeshes = NULL;
if (root->mNumMeshes)
pMeshes = root->mMeshes = new unsigned int[root->mNumMeshes];
if (root->mNumChildren)
ppcChildren = root->mChildren = new aiNode*[root->mNumChildren];
// generate the camera
if (hasCam)
{
aiNode* nd = *ppcChildren = new aiNode();
nd->mName.Set("<NFF_Camera>");
nd->mParent = root;
// allocate the camera in the scene
pScene->mNumCameras = 1;
pScene->mCameras = new aiCamera*[1];
aiCamera* c = pScene->mCameras[0] = new aiCamera;
c->mName = nd->mName; // make sure the names are identical
c->mHorizontalFOV = AI_DEG_TO_RAD( angle );
c->mLookAt = camLookAt - camPos;
c->mPosition = camPos;
c->mUp = camUp;
// If the resolution is not specified in the file, we
// need to set 1.0 as aspect.
c->mAspect = (!resolution.y ? 0.f : resolution.x / resolution.y);
++ppcChildren;
}
// generate light sources
if (!lights.empty())
{
pScene->mNumLights = (unsigned int)lights.size();
pScene->mLights = new aiLight*[pScene->mNumLights];
for (unsigned int i = 0; i < pScene->mNumLights;++i,++ppcChildren)
{
const Light& l = lights[i];
aiNode* nd = *ppcChildren = new aiNode();
nd->mParent = root;
nd->mName.length = ::sprintf(nd->mName.data,"<NFF_Light%i>",i);
// allocate the light in the scene data structure
aiLight* out = pScene->mLights[i] = new aiLight();
out->mName = nd->mName; // make sure the names are identical
out->mType = aiLightSource_POINT;
out->mColorDiffuse = out->mColorSpecular = l.color * l.intensity;
out->mPosition = l.position;
}
}
if (!pScene->mNumMeshes)throw DeadlyImportError("NFF: No meshes loaded");
pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes];
for (it = meshes.begin(), m = 0; it != end;++it)
{
if ((*it).faces.empty())continue;
const MeshInfo& src = *it;
aiMesh* const mesh = pScene->mMeshes[m] = new aiMesh();
mesh->mNumVertices = (unsigned int)src.vertices.size();
mesh->mNumFaces = (unsigned int)src.faces.size();
// Generate sub nodes for named meshes
if (src.name[0])
{
aiNode* const node = *ppcChildren = new aiNode();
node->mParent = root;
node->mNumMeshes = 1;
node->mMeshes = new unsigned int[1];
node->mMeshes[0] = m;
node->mName.Set(src.name);
// setup the transformation matrix of the node
aiMatrix4x4::FromToMatrix(aiVector3D(0.f,1.f,0.f),
src.dir,node->mTransformation);
aiMatrix4x4& mat = node->mTransformation;
mat.a1 *= src.radius.x; mat.b1 *= src.radius.x; mat.c1 *= src.radius.x;
mat.a2 *= src.radius.y; mat.b2 *= src.radius.y; mat.c2 *= src.radius.y;
mat.a3 *= src.radius.z; mat.b3 *= src.radius.z; mat.c3 *= src.radius.z;
mat.a4 = src.center.x;
mat.b4 = src.center.y;
mat.c4 = src.center.z;
++ppcChildren;
}
else *pMeshes++ = m;
// copy vertex positions
mesh->mVertices = new aiVector3D[mesh->mNumVertices];
::memcpy(mesh->mVertices,&src.vertices[0],
sizeof(aiVector3D)*mesh->mNumVertices);
// NFF2: there could be vertex colors
if (!src.colors.empty())
{
ai_assert(src.colors.size() == src.vertices.size());
// copy vertex colors
mesh->mColors[0] = new aiColor4D[mesh->mNumVertices];
::memcpy(mesh->mColors[0],&src.colors[0],
sizeof(aiColor4D)*mesh->mNumVertices);
}
if (!src.normals.empty())
{
ai_assert(src.normals.size() == src.vertices.size());
// copy normal vectors
mesh->mNormals = new aiVector3D[mesh->mNumVertices];
::memcpy(mesh->mNormals,&src.normals[0],
sizeof(aiVector3D)*mesh->mNumVertices);
}
if (!src.uvs.empty())
{
ai_assert(src.uvs.size() == src.vertices.size());
// copy texture coordinates
mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
::memcpy(mesh->mTextureCoords[0],&src.uvs[0],
sizeof(aiVector3D)*mesh->mNumVertices);
}
// generate faces
unsigned int p = 0;
aiFace* pFace = mesh->mFaces = new aiFace[mesh->mNumFaces];
for (std::vector<unsigned int>::const_iterator it2 = src.faces.begin(),
end2 = src.faces.end();
it2 != end2;++it2,++pFace)
{
pFace->mIndices = new unsigned int [ pFace->mNumIndices = *it2 ];
for (unsigned int o = 0; o < pFace->mNumIndices;++o)
pFace->mIndices[o] = p++;
}
// generate a material for the mesh
aiMaterial* pcMat = (aiMaterial*)(pScene->mMaterials[m] = new aiMaterial());
mesh->mMaterialIndex = m++;
aiString s;
s.Set(AI_DEFAULT_MATERIAL_NAME);
pcMat->AddProperty(&s, AI_MATKEY_NAME);
// FIX: Ignore diffuse == 0
aiColor3D c = src.shader.color * (src.shader.diffuse.r ? src.shader.diffuse : aiColor3D(1.f,1.f,1.f));
pcMat->AddProperty(&c,1,AI_MATKEY_COLOR_DIFFUSE);
c = src.shader.color * src.shader.specular;
pcMat->AddProperty(&c,1,AI_MATKEY_COLOR_SPECULAR);
// NFF2 - default values for NFF
pcMat->AddProperty(&src.shader.ambient, 1,AI_MATKEY_COLOR_AMBIENT);
pcMat->AddProperty(&src.shader.emissive,1,AI_MATKEY_COLOR_EMISSIVE);
pcMat->AddProperty(&src.shader.opacity, 1,AI_MATKEY_OPACITY);
// setup the first texture layer, if existing
if (src.shader.texFile.length())
{
s.Set(src.shader.texFile);
pcMat->AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0));
if (aiTextureMapping_UV != src.shader.mapping) {
aiVector3D v(0.f,-1.f,0.f);
pcMat->AddProperty(&v, 1,AI_MATKEY_TEXMAP_AXIS_DIFFUSE(0));
pcMat->AddProperty((int*)&src.shader.mapping, 1,AI_MATKEY_MAPPING_DIFFUSE(0));
}
}
// setup the name of the material
if (src.shader.name.length())
{
s.Set(src.shader.texFile);
pcMat->AddProperty(&s,AI_MATKEY_NAME);
}
// setup some more material properties that are specific to NFF2
int i;
if (src.shader.twoSided)
{
i = 1;
pcMat->AddProperty(&i,1,AI_MATKEY_TWOSIDED);
}
i = (src.shader.shaded ? aiShadingMode_Gouraud : aiShadingMode_NoShading);
if (src.shader.shininess)
{
i = aiShadingMode_Phong;
pcMat->AddProperty(&src.shader.shininess,1,AI_MATKEY_SHININESS);
}
pcMat->AddProperty(&i,1,AI_MATKEY_SHADING_MODEL);
}
pScene->mRootNode = root;
}
#endif // !! ASSIMP_BUILD_NO_NFF_IMPORTER
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
] | [
[
[
1,
1256
]
]
] |
6254fab6b0cadcd80a87c20ccd21017e6b706648 | 4323418f83efdc8b9f8b8bb1cc15680ba66e1fa8 | /Trunk/Battle Cars/Battle Cars/Source/CHowToPlayState.cpp | 519a91fd83a6cf7c4c605adcc8a92417543e7c88 | [] | no_license | FiveFourFive/battle-cars | 5f2046e7afe5ac50eeeb9129b87fcb4b2893386c | 1809cce27a975376b0b087a96835347069fe2d4c | refs/heads/master | 2021-05-29T19:52:25.782568 | 2011-07-28T17:48:39 | 2011-07-28T17:48:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,210 | cpp |
#include "CHowToPlayState.h"
#include "CMainMenuState.h"
#include "CPrintFont.h"
#include "CSGD_TextureManager.h"
#include "CGame.h"
#include "CSGD_FModManager.h"
#include "CSGD_DirectInput.h"
#include "CSGD_Direct3D.h"
#include "CXboxInput.h"
#include "CKeyBinds.h"
enum menu {EXIT};
CHowToPlayState::CHowToPlayState(void)
{
m_pPF = NULL;
m_pTM = NULL;
m_pFM = NULL;
m_pDI = NULL;
m_pController1 = NULL;
m_pController2 = NULL;
}
CHowToPlayState::~CHowToPlayState(void)
{
}
CHowToPlayState::CHowToPlayState(const CHowToPlayState&)
{
}
CHowToPlayState& CHowToPlayState::operator=(const CHowToPlayState&)
{
return *this;
}
CHowToPlayState* CHowToPlayState::GetInstance(void)
{
static CHowToPlayState instance;
return &instance;
}
void CHowToPlayState::Enter(void)
{
m_pDI = CSGD_DirectInput::GetInstance();
m_pTM = CSGD_TextureManager::GetInstance();
m_pController1 = CGame::GetInstance()->GetController1();
m_pController2 = CGame::GetInstance()->GetController2();
m_nFontID = m_pTM->LoadTexture("resource/graphics/BC_Font.png",D3DCOLOR_XRGB(0, 0, 0));
m_pPF = new CPrintFont(m_nFontID);
m_pFM = CSGD_FModManager::GetInstance();
m_nMenuSelect = m_pFM->LoadSound("resource/sounds/menuselect.mp3");
m_nMenuMove = m_pFM->LoadSound("resource/sounds/menuchange.mp3");
m_nBGImageID = m_pTM->LoadTexture("resource/graphics/gamestates images/optionstate.jpg");
m_pFM->SetVolume(m_nMenuSelect,CGame::GetInstance()->getSoundAVolume());
m_pFM->SetVolume(m_nMenuMove,CGame::GetInstance()->getSoundAVolume());
}
void CHowToPlayState::Exit(void)
{
delete m_pPF;
}
bool CHowToPlayState::Input(void)
{
if(CGame::GetInstance()->ControllerInput())
{
//m_pController1->ReadInputState();
XINPUT_STATE xState = m_pController1->GetState();
BYTE rTrig = xState.Gamepad.bRightTrigger;
CKeyBinds* tempkeys = m_pController1->GetKB();
float x = xState.Gamepad.sThumbLX;
float y = xState.Gamepad.sThumbLY;
if(CGame::GetInstance()->GetInputDelay() >= 0.15f)
{
if(xState.Gamepad.wButtons & XINPUT_GAMEPAD_B)
{
CGame::GetInstance()->ResetInputDelay();
return HandleEnter();
}
}
if(CGame::GetInstance()->GetThumbDelay() >= 0.15f)
{
CGame::GetInstance()->ResetThumbDelay();
}
}
else
{
if(m_pDI->KeyPressed(DIK_ESCAPE)||m_pDI->JoystickButtonPressed(1))
{
CGame::GetInstance()->RemoveState(this);
}
if(m_pDI->KeyPressed(DIK_RETURN)||m_pDI->JoystickButtonPressed(0))
{
return this->HandleEnter();
}
}
return true;
}
void CHowToPlayState::Update(float fElapsedTime)
{
m_pFM->Update();
}
void CHowToPlayState::Render(void)
{
CSGD_Direct3D* pD3D = CSGD_Direct3D::GetInstance();
m_pTM->Draw(m_nBGImageID, 0, 0, 1.0f, 1.0f);
m_pPF->PrintCentered("HOW TO PLAY",CGame::GetInstance()->GetScreenWidth()/2,50,2.0f,D3DCOLOR_XRGB(255, 0, 0));
m_pPF->Print("Keyboard",250,130,1.5f,D3DCOLOR_XRGB(0,0,255));
m_pPF->Print("Arrow Keys - MOVEMENT",200,250,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Spacebar - SHOOT",200,300,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Left Control - CHANGE WEAPONS",200,350,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Escape - PAUSE",200,400,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Enter - CONTINUE",200,450,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Keyboard",850,130,1.5f,D3DCOLOR_XRGB(0,0,255));
m_pPF->Print("Left Stick - Steering",800,250,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("X - SHOOT",800,300,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Left Bumper - CHANGE WEAPONS",800,350,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Start - PAUSE",800,400,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Right Trigger - Accelerate",800,450,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->Print("Left Trigger - Break/Reverse",800,600,0.7f,D3DCOLOR_XRGB(0, 0, 255));
m_pPF->PrintCentered("PRESS ESC OR B (GAMEPAD) TO EXIT",CGame::GetInstance()->GetScreenWidth()/2,800,1.0f,D3DCOLOR_XRGB(0, 255, 0));
}
bool CHowToPlayState::HandleEnter(void)
{
m_pFM->PlaySound(m_nMenuSelect);
CGame::GetInstance()->RemoveState(this);
return true;
} | [
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330",
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330"
] | [
[
[
1,
52
],
[
54,
148
]
],
[
[
53,
53
]
]
] |
c4f008c8af009e002b160158bd766d9126c25247 | 6630a81baef8700f48314901e2d39141334a10b7 | /1.4/Testing/Cxx/swWxGuiTesting/swWxGuiTestTempInteractive.cpp | 759f64fa3d499f0a91ececaa17d55835519758f5 | [] | no_license | jralls/wxGuiTesting | a1c0bed0b0f5f541cc600a3821def561386e461e | 6b6e59e42cfe5b1ac9bca02fbc996148053c5699 | refs/heads/master | 2021-01-10T19:50:36.388929 | 2009-03-24T20:22:11 | 2009-03-26T18:51:24 | 623,722 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,080 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: swWxGuiTesting/swWxGuiTestTempInteractive.cpp
// Author: Reinhold Füreder
// Created: 2004
// Copyright: (c) 2005 Reinhold Füreder
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "swWxGuiTestTempInteractive.h"
#endif
#include "swWxGuiTestTempInteractive.h"
#include "wx/dialog.h"
#include "swWxGuiTestHelper.h"
#include "swWxGuiTestTempInteractiveControl.h"
#include "swWxLogicErrorException.h"
namespace swTst {
WxGuiTestTempInteractive::WxGuiTestTempInteractive ()
{
m_dialog = NULL;
m_file = NULL;
m_line = -1;
}
WxGuiTestTempInteractive::~WxGuiTestTempInteractive ()
{
if (m_dialog != NULL) {
m_dialog->PopEventHandler (true);
m_dialog->Destroy ();
}
if (m_file != NULL) {
delete [] m_file;
}
}
void WxGuiTestTempInteractive::ShowCurrentGui ()
{
if (WxGuiTestHelper::GetDisableTestInteractivity ()) {
return;
}
// Store old main loop flag and set new one:
bool oldUseExitMainLoopOnIdle = WxGuiTestHelper::GetUseExitMainLoopOnIdleFlag ();
WxGuiTestHelper::SetUseExitMainLoopOnIdleFlag (false);
// Likewise, provide normal (= release, in opposition to testing mode)
// behaviour:
bool oldShowModalDialogsNonModal = WxGuiTestHelper::GetShowModalDialogsNonModalFlag ();
WxGuiTestHelper::SetShowModalDialogsNonModalFlag (false);
bool oldShowPopupMenus = WxGuiTestHelper::GetShowPopupMenusFlag ();
WxGuiTestHelper::SetShowPopupMenusFlag (true);
if (m_dialog == NULL) {
this->CreateDialog ();
m_dialog->PushEventHandler (new WxGuiTestTempInteractiveControl (
m_dialog));
}
m_dialog->Show ();
// Main loop will be exited in WxGuiTestTempInteractiveControl::OnOK()
wxTheApp->MainLoop ();
// Restore main loop flag:
WxGuiTestHelper::SetUseExitMainLoopOnIdleFlag (oldUseExitMainLoopOnIdle);
// Likewise, restore other flags:
WxGuiTestHelper::SetShowModalDialogsNonModalFlag (oldShowModalDialogsNonModal);
WxGuiTestHelper::SetShowPopupMenusFlag (oldShowPopupMenus);
}
void WxGuiTestTempInteractive::ShowCurrentGui (const char *file, int line)
{
if (!file) {
return;
}
if (strcmp (file, "") == 0) {
throw sw::WxLogicErrorException ("WxGuiTestTempInteractive: Empty filename");
}
if (m_file) {
delete [] m_file;
}
m_file = new char[strlen(file) + 1];
strcpy (m_file, file);
if (line < 0) {
throw sw::WxLogicErrorException ("WxGuiTestTempInteractive: Invalid line number");
}
m_line = line;
this->ShowCurrentGui ();
}
void WxGuiTestTempInteractive::CreateDialog ()
{
m_dialog = new wxDialog (wxTheApp->GetTopWindow (), -1,
_("wxGui CppUnit Testing Suspended"), wxDefaultPosition,
wxDefaultSize, wxDEFAULT_DIALOG_STYLE);
wxBoxSizer *sizer = new wxBoxSizer (wxVERTICAL);
wxStaticText *text = new wxStaticText (m_dialog, -1,
_("Temporary interactive test. -- Continue unit testing?"),
wxDefaultPosition, wxDefaultSize, 0);
sizer->Add (text, 0, wxALIGN_CENTER | wxALL, 10);
if ((m_file) && (m_line > -1)) {
wxStaticText *fileInfoText = new wxStaticText (m_dialog, -1,
wxString::Format ("%s: %s\n%s: %d", _("File"), m_file,
_("Line"), m_line), wxDefaultPosition, wxDefaultSize, 0);
sizer->Add (fileInfoText, 0, wxALIGN_CENTER | wxALL, 10);
}
wxButton *okBtn = new wxButton (m_dialog, -1, _("OK"), wxDefaultPosition,
wxDefaultSize, 0);
sizer->Add (okBtn, 0, wxALIGN_CENTER | wxALL, 10);
m_dialog->SetSizer (sizer);
sizer->SetSizeHints (m_dialog);
m_dialog->Layout ();
}
} // End namespace swTst
| [
"john@64288482-8357-404e-ad65-de92a562ee98"
] | [
[
[
1,
143
]
]
] |
881f44ebe35ab4417028af616e834b9ebde4555e | c7521fa1601bf7a9d63fed1b76ca09e2d8352e92 | /apps/SandBox/oFSSAODoF/src/addons/ofxShader/src/ofxShader.h | 69ff934cbf63a80dbc45c626b989bbed38916d6f | [] | no_license | Akira-Hayasaka/YES-NO | 3277d7b86c74abdaf32b7d76a819b8d08eef4481 | 74b2b60a5b8e7777ce6c595b82c082945665637a | refs/heads/master | 2021-01-16T01:07:31.340567 | 2011-03-25T23:09:41 | 2011-03-25T23:09:41 | 31,582,343 | 1 | 0 | null | 2015-03-03T06:06:23 | 2015-03-03T06:06:21 | null | UTF-8 | C++ | false | false | 3,230 | h | #pragma once
/*
todo: add support for attachment of multiple shaders
if a uniform or attribute isn't available, this will cause an error
make sure to catch and report that error.
*/
#include "ofMain.h"
#include <fstream>
class ofxShader {
public:
ofxShader();
~ofxShader();
void setup(string shaderName);
void setup(string vertexName, string fragmentName);
void setupInline(string vertexShaderSource, string fragmentShaderSource);
void unload();
void begin();
void end();
// set a texture reference
void setTexture(const char* name, ofBaseHasTexture& img, int textureLocation);
void setTexture(const char* name, ofTexture& img, int textureLocation);
// set a single uniform value
void setUniform1i(const char* name, int v1);
void setUniform2i(const char* name, int v1, int v2);
void setUniform3i(const char* name, int v1, int v2, int v3);
void setUniform4i(const char* name, int v1, int v2, int v3, int v4);
void setUniform1f(const char* name, float v1);
void setUniform2f(const char* name, float v1, float v2);
void setUniform3f(const char* name, float v1, float v2, float v3);
void setUniform4f(const char* name, float v1, float v2, float v3, float v4);
// set an array of uniform values
void setUniform1iv(const char* name, int* v, int count = 1);
void setUniform2iv(const char* name, int* v, int count = 1);
void setUniform3iv(const char* name, int* v, int count = 1);
void setUniform4iv(const char* name, int* v, int count = 1);
void setUniform1fv(const char* name, float* v, int count = 1);
void setUniform2fv(const char* name, float* v, int count = 1);
void setUniform3fv(const char* name, float* v, int count = 1);
void setUniform4fv(const char* name, float* v, int count = 1);
// set attributes that vary per vertex (look up the location before glBegin)
GLint getAttributeLocation(const char* name);
void setAttribute1s(GLint location, short v1);
void setAttribute2s(GLint location, short v1, short v2);
void setAttribute3s(GLint location, short v1, short v2, short v3);
void setAttribute4s(GLint location, short v1, short v2, short v3, short v4);
void setAttribute1f(GLint location, float v1);
void setAttribute2f(GLint location, float v1, float v2);
void setAttribute3f(GLint location, float v1, float v2, float v3);
void setAttribute4f(GLint location, float v1, float v2, float v3, float v4);
void setAttribute1d(GLint location, double v1);
void setAttribute2d(GLint location, double v1, double v2);
void setAttribute3d(GLint location, double v1, double v2, double v3);
void setAttribute4d(GLint location, double v1, double v2, double v3, double v4);
void printActiveUniforms();
void printActiveAttributes();
GLuint vertexShader;
GLuint fragmentShader;
GLuint program;
protected:
string loadTextFile(string filename);
GLint getUniformLocation(const char* name);
void compileShader(GLuint shader, string source, string type);
void checkProgramInfoLog(GLuint program);
bool checkShaderLinkStatus(GLuint shader, string type);
bool checkShaderCompileStatus(GLuint shader, string type);
void checkShaderInfoLog(GLuint shader, string type);
bool bLoaded;
};
| [
"[email protected]"
] | [
[
[
1,
87
]
]
] |
7db0a92512acd3cce972d85a45dfb7fef0d135a9 | a841c4a8db70eac01125b85de02c68714fe71fcc | /Src/Hexxagon/SenceRender/SenceRender.hpp | 9ce2cd4e5ac9b46f97c2bf6015264c3dacab2262 | [] | no_license | Iceyer/seedcup2009 | 73c3020806f753b30fab618a7bfd3da8f8441337 | de5fce458116e2c71440cf733aaeb1cc55b2440c | refs/heads/master | 2016-09-05T12:12:02.101164 | 2010-02-02T04:10:54 | 2010-02-02T04:10:54 | 32,113,136 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,998 | hpp | //Header file for render sence
#pragma once
#include "../../GameCore/Map.hpp"
#include "../GameCore/Game.hpp"
const COLORREF gColorRed = RGB(255, 0, 0);
const COLORREF gColorGreen = RGB(0, 255, 0);
const COLORREF gColorBlue = RGB(0, 0, 255);
const COLORREF gColorYellow = RGB(255, 255, 0);
const COLORREF gColorWhite = RGB(255, 255, 255);
const COLORREF gColorBlack = RGB(0, 0, 0);
const COLORREF gColorGrey200 = RGB(200, 200, 200);
const COLORREF gBackGroundColor = gColorBlack;
class CDC;
class Render
{
public:
~Render();
public:
static Render& SRender()
{
return m_Render;
}
void SetDC(CDC *pdc);
void Render::SetSenceSize(int x, int y);
void DrawPreScreen();
void RenderSence();
void DrawMatchEndInfo();
void RenderMoveAction(const Action& curAction);
void EnableMoveAction();
bool IsMoveActionEnd();
//获得某一贴图的左上角的像素坐标
inline CPoint LogicPos2PixelPos(int x, int y);
//初始化成员变量
void Init();
void DrawGameInfo();
void DrawHexagon(int cx, int cy, unsigned BitmapID, unsigned BkBitmapID, Hexxagon::MapItem::ItemType iType = Hexxagon::MapItem::EMPTY);
void DrawPlayer1(int cx, int cy);
void DrawPlayer2(int cx, int cy);
void ShowResultSwitch();
private:
Render();
static Render m_Render;
CDC *m_pDC;
int m_Width;
int m_Height;
int m_iStartX; //记录整个贴图的左上角x坐标
int m_iStartY; //记录整个贴图的左上角y坐标
int m_iMapWidth; //记录横向有多少个hole
int m_iMapHeight; //记录纵向有多少个hole
CFont m_PlayerInfoFont;
CFont m_PreInfoFont;
CPoint m_PosStart;
CPoint m_PosEnd;
CPoint m_CurPos;
public:
bool m_bMoveAction;
bool m_bMoving;
bool m_showResult;
}; | [
"icesyaoran@c2d47732-b0c4-11de-9c04-c7668166297d",
"[email protected]@c2d47732-b0c4-11de-9c04-c7668166297d"
] | [
[
[
1,
3
],
[
7,
12
],
[
14,
33
],
[
36,
37
],
[
39,
39
],
[
51,
51
],
[
53,
53
],
[
61,
68
],
[
85,
85
]
],
[
[
4,
6
],
[
13,
13
],
[
34,
35
],
[
38,
38
],
[
40,
50
],
[
52,
52
],
[
54,
60
],
[
69,
84
]
]
] |
b8a0f88c503ff2c70a7bfdf12714956299464cab | 4b111d57027ac3a21af503aa5344a2e9f7e09746 | /ndefnfcmimeimagerecord.cpp | b4bc17d9105ba17c1cf219ccec9e14cad2c346b2 | [] | no_license | ginggs/nfcwriter | 8d713da10041a6bb8c8cbc178081083807ba3e28 | 6b59ab5348c34c5b05da70f1561610e9ac17d86a | refs/heads/master | 2020-12-24T22:59:03.309554 | 2011-11-21T21:19:07 | 2011-11-21T21:19:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,238 | cpp | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Andreas Jakl ([email protected])
**
** This file is part of an NFC example for Qt Mobility.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "ndefnfcmimeimagerecord.h"
/*!
\brief Construct a new Mime/Image record using the default type (png)
and an empty payload.
*/
NdefNfcMimeImageRecord::NdefNfcMimeImageRecord()
: QNdefRecord(IMAGERECORD_DEFAULT_TNF, IMAGERECORD_DEFAULT_TYPE)
{
setPayload(IMAGERECORD_DEFAULT_PAYLOAD);
}
/*!
\brief Create a new Mime/Image record based on the record passed
through the argument.
*/
NdefNfcMimeImageRecord::NdefNfcMimeImageRecord(const QNdefRecord &other)
: QNdefRecord(other)
{
}
/*!
\brief Create a new Mime/Image record using the specified mime type
and an empty payload.
*/
NdefNfcMimeImageRecord::NdefNfcMimeImageRecord(const QByteArray &mimeType)
: QNdefRecord(IMAGERECORD_DEFAULT_TNF, mimeType)
{
setPayload(IMAGERECORD_DEFAULT_PAYLOAD);
}
/*!
\brief Create a new Mime/Image record using the pixel data of the \a img,
converted and encoded in the specified mime type (if supported).
The mime type can either be a Qt image format or a mime type - the method
will automatically convert to a mime type (\see setImage() ).
*/
NdefNfcMimeImageRecord::NdefNfcMimeImageRecord(const QImage &img, const QByteArray &mimeType)
: QNdefRecord(IMAGERECORD_DEFAULT_TNF, mimeType)
{
setImage(img, mimeType);
}
/*!
\brief Decode the payload and return it as a pixel image (QImage).
If the payload is empty or Qt cannot parse the decode the image format,
an empty image is returned.
\return the decoded image if possible, or an empty image otherwise.
*/
QImage NdefNfcMimeImageRecord::image() const
{
const QByteArray p = payload();
if (p.isEmpty())
return QImage();
QImage img;
if (img.loadFromData(p))
{
return img;
}
return QImage();
}
/*!
\brief Get the raw data of the image.
No decoding is performed, so this will retrieve the encoded version
of the image (e.g., a png). This equals retrieving the payload.
\return the encoded image / payload of the record.
*/
QByteArray NdefNfcMimeImageRecord::imageRawData() const
{
return payload();
}
/*!
\brief Set the image (= payload) of the record to the byte array.
This allows passing an encoded image (e.g., png) directly to the class.
The method will attempt to identify the mime type of the raw image data
and automatically modify the mime type stored in the record if successful.
If this is not possible or the passed byte array is empty, the payload
will not be set.
\param imageRawData the encoded image data to use as payload of the record.
*/
bool NdefNfcMimeImageRecord::setImage(QByteArray& imageRawData)
{
if (imageRawData.isEmpty())
return false;
// Check image mime type
QBuffer buffer(&imageRawData); // compiler warning: taking address of temporary
buffer.open(QIODevice::ReadOnly);
QByteArray imgFormat = QImageReader::imageFormat(&buffer);
// Check if Qt supports the image format (needed to set the mime type automatically)
if (imgFormat.isEmpty())
return false;
// Add "image/" to the Qt image type in order to get to a mime type
imgFormat = imgFormat.toLower();
imgFormat = imgFormat.prepend("image/");
setType(imgFormat);
setPayload(imageRawData);
return true;
}
/*!
\brief Encode the image data into the payload using the specified mime type.
\param image the pixel image data to encode and set as the payload.
\param mimeType the mime type can either be specified using a supported mime
type or a Qt image format. The image format is automatically converted to a
mime type.
*/
bool NdefNfcMimeImageRecord::setImage(const QImage &image, const QByteArray &mimeType)
{
// See if we support writing the image in the specified type
QByteArray checkedFormat = checkImageFormat(mimeType);
if (checkedFormat.isEmpty())
return false;
QByteArray p;
QBuffer buffer(&p);
buffer.open(QIODevice::WriteOnly);
bool success = image.save(&buffer, checkedFormat.constData()); // writes image into p in the selected format
if (!success) {
return false;
}
setPayload(p);
return true;
}
/*!
\brief Retrieve the Qt image format of the image data stored in the payload.
\see QImageReader::imageFormat()
\return the Qt image format of the payload.
*/
QByteArray NdefNfcMimeImageRecord::format() const
{
QByteArray p = payload();
if (p.isEmpty())
return QByteArray();
QBuffer buffer(&p); // compiler warning: taking address of temporary
buffer.open(QIODevice::ReadOnly);
return QImageReader::imageFormat(&buffer);
}
/*!
\brief return the mime type of the image, as set in the record type.
\return the mime type of the record.
*/
QByteArray NdefNfcMimeImageRecord::mimeType() const
{
return type();
}
/*!
\brief Check if the specified Qt image \a format / mime type is supported by Qt
for encoding and return it as a Qt image format name.
\param format either a Qt image format (e.g., "png") or a mime type
(e.g., "image/png").
\return if the image format is supported by Qt for encoding, the Qt image format
name. If the type is not supported, an empty byte array is returned.
*/
QByteArray NdefNfcMimeImageRecord::checkImageFormat(const QByteArray& format)
{
// Convert MIME types to Qt image type names
QByteArray checkFormat = format.toUpper();
if (checkFormat.startsWith("IMAGE/")) {
// Remove leading "image/" from the mime type so that only the image
// type is left
checkFormat = checkFormat.right(checkFormat.size() - 6);
}
// Check if the image format is supported by Qt
bool supported = false;
foreach (QByteArray supportedFormat, QImageWriter::supportedImageFormats()) {
if (checkFormat == supportedFormat) {
supported = true;
break;
}
}
if (supported) {
return checkFormat;
} else {
return QByteArray();
}
}
| [
"[email protected]"
] | [
[
[
1,
239
]
]
] |
b3c2df1897c99e7c88686f2ed9608dcda8d8c160 | e8d9619e262531453688550db22d0e78f1b51dab | /sametime/.svn/text-base/userlist.h.svn-base | be674b0e5f00cee2e6c684dbdf0ad6d9b1dc4edc | [] | no_license | sje397/sje-miranda-plugins | e9c562f402daef2cfbe333ce9a8a888cd81c9573 | effb7ea736feeab1c68db34a86da8a2be2b78626 | refs/heads/master | 2016-09-05T16:42:34.162442 | 2011-05-22T14:48:15 | 2011-05-22T14:48:15 | 1,784,020 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,242 | #ifndef _USERLIST_INC
#define _USERLIST_INC
#include "common.h"
#include "utils.h"
#include <fstream>
#include <string>
#include <iostream>
#include "clist_util.h"
typedef struct {
int cbSize;
char *nick;
char *firstName;
char *lastName;
char *email;
char reserved[16];
char name[256];
char stid[256];
bool group;
} MYPROTOSEARCHRESULT;
typedef struct {
size_t nSize;
int nFieldCount;
TCHAR ** pszFields;
MYPROTOSEARCHRESULT psr;
} MYCUSTOMSEARCHRESULTS;
HANDLE FindContactByUserId(const char *id);
bool GetAwareIdFromContact(HANDLE hContact, mwAwareIdBlock *id_block);
int SearchForUser(const char *name);
int GetMoreDetails(const char *name);
int CreateSearchDialog(WPARAM wParam, LPARAM lParam);
int SearchFromDialog(WPARAM wParam, LPARAM lParam);
HANDLE AddSearchedUser(MYPROTOSEARCHRESULT *mpsr, bool temporary);
HANDLE AddContact(mwSametimeUser *user, bool temporary);
void UserListCreate();
void UserListAddStored();
void UserListDestroy();
void ImportContactsFromFile(TCHAR *filename);
void ExportContactsToServer();
void UserRecvAwayMessage(HANDLE hContact);
void InitUserList(mwSession *session);
void DeinitUserList(mwSession *session);
#endif | [
"[email protected]"
] | [
[
[
1,
59
]
]
] |
|
5b410923cc14faf6a6a622d5c0076e881e8b9633 | 26d2b43b622326b792d1e7a8988bc54d02a5d382 | /src/surfaces.h | d77c4b5cae4e4090a4f8a485a32a63a3bc5425f9 | [] | no_license | rehno-lindeque/osi-glge | cbfc8ad6f5d15236ec46d280f39f57e9fefdb21f | 6b60fe6a47f5b667bf5ff31d51a559199f96c48c | refs/heads/master | 2021-01-19T21:52:17.218139 | 2011-01-29T09:57:27 | 2011-01-29T09:57:27 | 1,303,689 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 626 | h | #ifndef __GLGE_SURFACES_H__
#define __GLGE_SURFACES_H__
//////////////////////////////////////////////////////////////////////////////
//
// SURFACES.H
//
// Copyright © 2006, Rehno Lindeque. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////
/* DOCUMENTATION */
/*
DESCRIPTION:
GLGE Surfaces
*/
namespace GLGE
{
/* CLASSES */
class GLSurfaces : public BaseGE::Surfaces
{
public:
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
fb3df95428238ec7a9ef5174faae0cf6c3d1815e | 5e0422794380a8f3bf06d0c37ac2354f4b91fefb | /server/stdafx.h | ae8c41d876a529d5efa82b67b0758a929dbf099c | [] | no_license | OrAlien/fastnetwork | 1d8fb757b855b1f23cc844cda4d8dc7a568bc38e | 792d28d8b5829c227aebe8378f60db17de4d6f14 | refs/heads/master | 2021-05-28T20:30:24.031458 | 2010-06-02T14:30:04 | 2010-06-02T14:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
#include <iostream>
#include <string>
using namespace std;
#include <boost/any.hpp>
#include <boost/array.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/smart_ptr.hpp>
using namespace boost;
#include <boost/asio.hpp>
using namespace boost::asio;
#include <fastnetwork/fastnetwork.h>
using namespace fastnetwork;
#define ENABLE_LOG
#include "log.h"
| [
"everwanna@8b0bd7a0-72c1-11de-90d8-1fdda9445408"
] | [
[
[
1,
35
]
]
] |
b572b765e80f1b5b626206a40db4a5ef5542df24 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/TcpSymbianSerial/symbian-r6/SendDataReceiver.h | 1d1b5b704a8342c7cb15145ad1ecf73e511f2b2a | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,972 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SENDDATARECEIVER_H
#define SENDDATARECEIVER_H
#include <e32base.h>
/**
* This class enqueues the data that should be sent to a remote host
* and portions it out in a suitable pace.
* The queue contains data that is pushed in one thread and popped in
* another.
*/
class CSendDataReceiver : public CActive
{
/** A critical section for serialized access to the queue.*/
class RCriticalSection iCritical;
/** Pointer to the "gateway" to the main module class. */
class CTcpAdmin* iAdmin;
/**
* The thread if of the thread this object is running in. This is
* the same thread that is popping data from thge queue.
*/
class TThreadId iThreadId;
/** The queue of data. */
CArrayPtrSeg<HBufC8>* iQueue;
/** @name Constructors and destructor. */
//@{
/**
* Constructor.
* @param aAdmin the owner.
* @param aThreadId the thread id of the thread this object is running in.
*/
CSendDataReceiver(class CTcpAdmin* aAdmin, class TThreadId aThreadId);
/** Second phase constructor. */
void ConstructL();
public:
/**
* Static constructor.
* @param aAdmin the owner.
* @param aThreadId the thread id of the thread this object is running in.
*/
static class CSendDataReceiver* NewL(class CTcpAdmin* aAdmin,
class TThreadId aThreadId);
/** Virtual destructor. */
virtual ~CSendDataReceiver();
//}@
private:
/** @name From CActive. */
//@{
virtual void RunL();
virtual void DoCancel();
//@}
public:
/**
* Sets the object as active. The request will complete when there
* is data available for writing.
*/
void RequestData();
/**
* The SendData function is available as leaving and non-leaving
* function.
* The function is supposed to be called from another thread with
* data that will be written by the thread this object runs in.
* The data is enqueued and if the object is currently waiting for
* data the object will be marked for completion in the proper
* thread.
* @param aData the data.
* @param aLength the amount of data.
*/
//@{
/** @return One of the system wide error codes. */
TInt SendData(const TUint8* aData, TUint aLength);
void SendDataL(const TUint8* aData, TUint aLength);
//@}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
90
]
]
] |
01ac7db8ede5371e9795cad84755fa9a0ac104f7 | 6bf6be46f9e46950e56da6b10ebb103959dcfac7 | /1/UDP/UDP.cpp | f1e19544271bc30b329984b5fa31e023e500b31c | [] | no_license | tr00per/pus-casa | 42556787b87c4fff4e57d7d41f9895c6339a3186 | f1ea1758194879da4d2a7f42eee2690f4d686fdf | refs/heads/master | 2016-09-06T12:17:04.486620 | 2010-03-29T07:24:26 | 2010-03-29T07:24:26 | 32,858,134 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 11,030 | cpp | // UDP.cpp : UDP client and server
//
//Windows Sockets error codes: http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx
#include "stdafx.h"
#include <winsock2.h>
#include <ws2tcpip.h> //newer functions and structs used to retrieve IP addresses
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <AtlBase.h> //parameter conversion
#include <AtlConv.h>
#include <WinBase.h> //directory listing
#include <list> //for queueing clients' queries
#define QUERYPORT 4000 //Diablo II port
#define DATAPORT 23073 //Soldat dedicated server port
#define BUFFLEN 512 //cannot exceed packet capacity
#define ROOTDIRLEN 128 //nostalgy
#define IPADDRLEN 16 //abc.def.ghi.jkl
SOCKET querySocket = INVALID_SOCKET;
SOCKET dataSocket = INVALID_SOCKET;
char serverAddress[IPADDRLEN];
char clientQuery[BUFFLEN];
char serverRoot[ROOTDIRLEN];
char transBuffer[BUFFLEN];
struct ClientRequest {
sockaddr * address;
int addressSize;
char ip[IPADDRLEN];
char query[BUFFLEN];
int querySize;
ClientRequest(sockaddr_in& addr, int size, const char * q, int qLen);
~ClientRequest();
};
void showUsageHelp();
void listDirectory(std::string& path, std::ostringstream& response);
void gatherOuputData(std::ostringstream& response);
void runServer();
void runClient();
int _tmain(int argc, _TCHAR* argv[])
{
enum {CLIENT, SERVER} state = CLIENT;
USES_CONVERSION;
if (argc == 2) {
//WISH check for trailing / in the name
//WISH check if the directory exists ^^
CT2CA arg_rootdir(argv[1]);
strncpy_s(serverRoot, arg_rootdir, ROOTDIRLEN-1);
serverRoot[ROOTDIRLEN-1] = '\0';
state = SERVER;
std::cout<<"Server root: "<<serverRoot<<std::endl;
} else if (argc == 3) {
//WISH check if input is correct (i.e. doesn't contain "..")
CT2CA arg_ip(argv[1]);
strncpy_s(serverAddress, arg_ip, IPADDRLEN-1);
serverAddress[IPADDRLEN-1] = '\0';
CT2CA arg_query(argv[2]);
strncpy_s(clientQuery, arg_query, BUFFLEN-1);
clientQuery[BUFFLEN-1] = '\0';
//state already set to CLIENT
std::cout<<"Server address: "<<serverAddress<<"\nClient query: "<<clientQuery<<std::endl;
} else {
showUsageHelp();
return 1;
}
//**** inicjalizuj Winsock
int error;
WSADATA wsaData;
//wersja 2.2; prosto z sierpnia 1997 roku ;P
if ((error = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0) {
std::cerr<<"WSAStartup returned an error: "<<error<<std::endl;
return 2;
}
//**** otwórz oba sockety
querySocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (querySocket == INVALID_SOCKET) {
std::cerr<<"Error while creating query socket: "<<WSAGetLastError()<<std::endl;
WSACleanup();
return 3;
}
dataSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (dataSocket == INVALID_SOCKET) {
std::cerr<<"Error while creating query socket: "<<WSAGetLastError()<<std::endl;
closesocket(querySocket);
WSACleanup();
return 3;
}
//**** wymuszenie obliczania sum kontrolnych
//dostępne do WinXP
bool optVal = true;
int optLen = sizeof(bool);
setsockopt(querySocket, IPPROTO_UDP, UDP_CHECKSUM_COVERAGE, (char*)&optVal, optLen);
setsockopt(dataSocket, IPPROTO_UDP, UDP_CHECKSUM_COVERAGE, (char*)&optVal, optLen);
sockaddr_in self;
self.sin_family = AF_INET;
self.sin_addr.s_addr = INADDR_ANY;
if (state == SERVER) {
self.sin_port = htons(QUERYPORT);
int binding = bind(querySocket, (sockaddr *)&self, sizeof(self));
if (binding == SOCKET_ERROR) {
std::cerr<<"Server bind() failed! Error code: "<<WSAGetLastError()<<std::endl;
} else {
runServer();
}
} else if (state == CLIENT) {
self.sin_port = htons(DATAPORT);
int binding = bind(dataSocket, (sockaddr *)&self, sizeof(self));
if (binding == SOCKET_ERROR) {
std::cerr<<"Client bind() failed! Error code: "<<WSAGetLastError()<<std::endl;
} else {
runClient();
}
}
//**** zakończ pracę z Winsock
closesocket(querySocket);
closesocket(dataSocket);
WSACleanup();
std::cout<<"Finished."<<std::endl;
return 0;
}
int recvfrom_to(SOCKET s, char * buf, int len, sockaddr * from, int * fromlen, long tv_sec, long tv_usec) {
timeval tv;
tv.tv_sec = tv_sec;
tv.tv_usec = tv_usec;
fd_set readfrom;
FD_ZERO(&readfrom);
FD_SET(s, &readfrom) ;
int t = select(0, &readfrom, 0, 0, &tv);
if (t == SOCKET_ERROR) {
return SOCKET_ERROR;
}
if (t > 0) {
if (FD_ISSET(s, &readfrom)) {
t = recvfrom(s, buf, len, 0, from, fromlen);
}
}
return t;
}
void runServer() {
bool running = true;
std::cout<<"Awaiting clients..."<<std::endl;
//**** przygotuj kolejkę dla klientów
std::list<ClientRequest *> queue;
typedef std::list<ClientRequest *>::iterator queueIter;
sockaddr_in peer;
int peerSize = sizeof(sockaddr_in);
while (running) {
ZeroMemory(&peer, peerSize);
//## recv query @ queueSocket
int trans = recvfrom_to(querySocket, clientQuery, BUFFLEN, (sockaddr *)&peer, &peerSize, 0, 100);
if (trans == SOCKET_ERROR) {
std::cerr<<"recvfrom_to() failed! Error code: "<<WSAGetLastError()<<std::endl;
return;
}
if (trans > 0) {
std::cout<<"New client connected!"<<std::endl;
if (strncmp(clientQuery, "~~kill", 6) == 0) {
running = false;
}
//## add to client queue
peer.sin_port = htons(DATAPORT); //zmień na port odbioru danych
ClientRequest * cr = new ClientRequest(peer, peerSize, clientQuery, trans);
queue.push_back(cr);
}
if (running && queue.size() > 0) {
//## handle first of queued clients
ClientRequest * cr = queue.front();
queue.pop_front();
strncpy_s(clientQuery, cr->query, strlen(cr->query));
std::ostringstream response;
std::cout<<"Handling client "<<cr->ip<<"..."<<std::endl;
std::cout<<"Query: "<<cr->query<<std::endl;
//## send data @ dataSocket
gatherOuputData(response);
std::string output;
int head = 0, tail = response.str().size();
int totalTrans = 0, recvAck;
do {
output = response.str().substr(head, BUFFLEN);
trans = sendto(dataSocket, output.c_str(), output.size(), 0, cr->address, cr->addressSize);
if (trans == SOCKET_ERROR) {
std::cerr<<"\nsendto() failed: "<<WSAGetLastError()<<std::endl;
break;
}
//## recv ack @ dataSocket
recvAck = recvfrom_to(dataSocket, transBuffer, BUFFLEN, cr->address, &(cr->addressSize), 30, 0);
if (recvAck == SOCKET_ERROR) {
std::cerr<<"\nrecvfrom_to() failed: "<<WSAGetLastError()<<std::endl;
break;
} else if (recvAck == 4 && strncmp("ACK", transBuffer, 3) == 0) {
head += BUFFLEN;
totalTrans += trans;
} else {
continue; //resend packet
}
} while (head < tail);
std::cout<<"Done\nAmount of data sent: "<<totalTrans<<std::endl;
}
}
//finalize
std::cout<<"Exiting..."<<std::endl;
if (queue.size() > 0) {
for (queueIter iter = queue.begin(); iter != queue.end(); ++iter) {
strncpy_s(clientQuery, "SHD", 4); //SDH - SHutDown
sendto(dataSocket, clientQuery, 4, 0, (*iter)->address, (*iter)->addressSize);
delete *iter;
}
}
}
void runClient() {
sockaddr_in srv;
int srvSize = sizeof(sockaddr_in);
srv.sin_family = AF_INET;
srv.sin_addr.s_addr = inet_addr(serverAddress);
srv.sin_port = htons(QUERYPORT);
//## send query @ queueSocket
int trans = sendto(querySocket, clientQuery, BUFFLEN, 0, (sockaddr *)&srv, srvSize);
if (trans == SOCKET_ERROR) {
std::cerr<<"sendto(QUERY) failed: "<<WSAGetLastError()<<std::endl;
return;
} else {
std::cout<<"Bytes sent: "<<trans<<std::endl;
}
//zmień port zapytania na port danych
srv.sin_port = htons(DATAPORT);
std::cout<<"\n\n";
int totalTrans = 0;
do {
//## recv data @ dataSocket
trans = recvfrom(dataSocket, transBuffer, BUFFLEN, 0, (sockaddr *)&srv, &srvSize);
if (trans == SOCKET_ERROR) {
std::cerr<<"recvfrom() failed! Error code: "<<WSAGetLastError()<<std::endl;
return;
}
std::cout.write(transBuffer, trans);
if (trans != 4 || strncmp("SHD", transBuffer, 3) != 0) {
totalTrans += trans;
//## send ack @ dataSocket
strncpy_s(clientQuery, "ACK", 4); //żeby ładnie zakończył stringa '\0'
int sendAck = sendto(dataSocket, clientQuery, 4, 0, (sockaddr *)&srv, srvSize);
if (sendAck == SOCKET_ERROR) {
std::cerr<<"sendto(ACK) failed! Error code: "<<WSAGetLastError()<<std::endl;
return;
}
}
if (trans < BUFFLEN) {
std::cout<<"\n\nTranssmision ended."<<std::endl;
}
} while (trans == BUFFLEN);
std::cout<<"Total bytes received: "<<totalTrans<<std::endl;
}
void showUsageHelp() {
std::cout
<<"Program usage:\n"
<<"{server.exe} <root dir>\n\n"
<<"<root dir>\tpath which will be used for translation of queries\n\t\tmaximum length is "<<ROOTDIRLEN<<"\n\n"
<<"Send \"~~kill\" to stop the server.\n\n"
<<"\n{client.exe} <host address> <query>\n\n"
<<"<host address>\tIPv4 address in a.b.c.d format\n"
<<"<query>\t\tfile to view or directory to list\n\t\tmaximum lenght is "<<BUFFLEN<<"; overlapping chars will be ignored\n\n"
<<std::flush;
}
void listDirectory(std::string& path, std::ostringstream& response) {
WIN32_FIND_DATAA search;
HANDLE h = FindFirstFileA((path+'*').c_str(), &search);
if (h == INVALID_HANDLE_VALUE) {
response<<"EMPTY!";
} else {
do {
response<<search.cFileName<<((search.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)? "/\n":"\n");
} while (FindNextFileA(h, &search));
FindClose(h);
}
}
void gatherOuputData(std::ostringstream& response) {
response.str("");
response<<serverRoot<<clientQuery;
std::string path = response.str();
std::cout<<"Opening and reading "<<path<<std::flush;
DWORD fileAttr = GetFileAttributesA(path.c_str());
//WISH check for trailing / when directory is recognized
response.str("");
if (fileAttr == INVALID_FILE_ATTRIBUTES) {
std::cout<<"\nPath is invalid! Sending root directory listing..."<<std::flush;
response<<"Invalid path! Root directory:\n";
path = serverRoot;
listDirectory(path, response);
} else if (fileAttr & FILE_ATTRIBUTE_DIRECTORY) {
std::cout<<"\nIt's a directory. Sending listing..."<<std::flush;
response<<"Listing directory:\n";
listDirectory(path, response);
} else {
std::ifstream fin(path.c_str());
char buf[BUFFLEN];
while (!fin.eof()) {
fin.read(buf, BUFFLEN);
response.write(buf, fin.gcount());
std::cout<<'.'<<std::flush;
}
fin.close();
std::cout<<"\nSending file content..."<<std::flush;
}
}
ClientRequest::ClientRequest(sockaddr_in& addr, int size, const char * q, int qLen): addressSize(size) {
address = new sockaddr();
memcpy((void *)address, (const void *)&addr, size);//HACK find a better way
strncpy_s(query, q, qLen);
strncpy_s(ip, inet_ntoa(addr.sin_addr), IPADDRLEN);
querySize = qLen;
}
ClientRequest::~ClientRequest() {
delete address;
}
| [
"arturczajka@f056a0d6-22c5-11df-a494-6dfd6523cf1c"
] | [
[
[
1,
364
]
]
] |
5fea85850b20ee996fe9891c503eb48f42b2e1ac | e8c9bfda96c507c814b3378a571b56de914eedd4 | /engineTest/MessageHandler.cpp | 899a6ac91dc424460199d404e0390c6f777807c4 | [] | no_license | VirtuosoChris/quakethecan | e2826f832b1a32c9d52fb7f6cf2d972717c4275d | 3159a75117335f8e8296f699edcfe87f20d97720 | refs/heads/master | 2021-01-18T09:20:44.959838 | 2009-04-20T13:32:36 | 2009-04-20T13:32:36 | 32,121,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,347 | cpp | #include <irrlicht.h>
#include <set>
#include "MessageHandler.h"
#include "GameEntity.h"
#include <iostream>
using std::cout;
MessageHandler::MessageHandler(){
}
MessageHandler::~MessageHandler(){
}
void MessageHandler::postMessage(Message_Type type, int delay, GameEntity *sender, GameEntity *receiver, const irr::ITimer* timer){
Message* m = new Message(delay + timer->getTime(), type, sender, receiver);
if(delay == 0){
deliverMessage(m);
}
else messageQueue.insert(m);
}
int MessageHandler::update(const irr::ITimer* timer){
//if(messageQueue.empty())return 0;
//working with delayed messages
while( !messageQueue.empty() && (*(messageQueue.begin()))->postTime < (int)timer->getTime()){
//deliverMessage(&*messageQueue.begin());
//deliverMessage(const_cast<const Message*>(& (*messageQueue.begin())) );
const Message* a = (*(messageQueue.begin()));
deliverMessage(a);
messageQueue.erase(messageQueue.begin());
}
return 0;
}
void MessageHandler::deliverMessage(const Message* m){
if(m->receiver->processMessage(m))
cout << "Message was handled.\n";
else cout<< "uh oh, message not handled\n";
delete m;
}
MessageHandler* MessageHandler::getInstance(){
static MessageHandler only_inst;
return &only_inst;
}
| [
"cthomas.mail@f96ad80a-2d29-11de-ba44-d58fe8a9ce33"
] | [
[
[
1,
64
]
]
] |
28da106ed5cfc8d1302918d3aad1652da6311341 | 0a169268d396fec311aa6028cb926922961e37e2 | /src/config.cc | d6a2c596d94a16c5b47c6833156f49cb0fda5a73 | [
"MIT"
] | permissive | silas/tyrion | a7391da442a1da96a6b71fb9a1e40d9dacdbd84a | c9b1b3335a589bef65e3ff75594981bad13bd938 | refs/heads/master | 2020-05-31T20:25:29.218916 | 2011-05-22T20:16:21 | 2011-05-22T20:16:21 | 1,182,734 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,644 | cc | /*
* Copyright (c) 2010, Silas Sewell
* All rights reserved.
*
* This file is subject to the MIT License (see the LICENSE file).
*/
#include "config.h"
#include <cctype>
#include <cstdlib>
#include "third_party/inih/ini.h"
namespace tyrion {
Config::Config(const std::string& filename) : error_(0), values_() {
error_ = ini_parse(filename.c_str(), ValueHandler, this);
}
int Config::ParseError() {
return error_;
}
bool Config::Has(const std::string& section, const std::string& name) {
return values_.count(MakeKey(section, name));
}
std::string Config::Get(const std::string& section, const std::string& name,
const std::string& default_value) {
std::string key = MakeKey(section, name);
return values_.count(key) ? values_[key] : default_value;
}
long Config::GetInt(const std::string& section, const std::string& name,
long default_value) {
std::string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
long n = strtol(value, &end, 0);
return end > value ? n : default_value;
}
std::string Config::MakeKey(const std::string& section,
const std::string& name) {
std::string key = section + "." + name;
for (size_t i = 0; i < key.length(); i++) {
key[i] = tolower(key[i]);
}
return key;
}
int Config::ValueHandler(void* user, const char* section, const char* name,
const char* value) {
Config* config = (Config*)user;
config->values_[MakeKey(section, name)] = value;
return 1;
}
} // namespace tyrion
| [
"[email protected]"
] | [
[
[
1,
59
]
]
] |
e1a5a46cda360b5a5067da92fb44511276800adb | f5b41ec38cf7640e37b880706bca424a19695afb | /Library/trunk/Library/Borrow.h | d90163ed85621419661d006b404e9e1593526fb9 | [] | no_license | dvirsegal/hw3-un | 99b3c5baac5667aba314efb002c6acfd52bba2de | ba83b06f3cb7e88ecd52bc08cf6a45828bc8ca5c | refs/heads/master | 2021-06-11T08:20:32.763185 | 2011-09-14T18:08:45 | 2011-09-14T18:08:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | h | /***************************************************************************
*
* HW 3
*
* Author: Dvir Segal
*
* Author: Sheira Ben Haim
**************************************************************************/
#ifndef _BORROW_H_
#define _BORROW_H_
#include <time.h>
#include <math.h>
class Borrow
{
private:
time_t _StartDate;
long _CID;
char* _type;
public:
Borrow():_type(NULL),_CID(0),_StartDate(time(NULL)){}//defualt c'tor
Borrow(time_t date):_type(NULL),_CID(0),_StartDate(date){}//c'tor
Borrow(long CID):_type(NULL),_CID( CID),_StartDate(time(NULL)){}//c'tor
Borrow(char* type, long CID):_type(type), _CID(CID){_StartDate=time(NULL);}//c'tor
long getCID() const {return _CID;}
void setBookType(char* type){_type=type;}
char* getBookType() const {return _type;}
time_t getStartDate() const {return _StartDate;}
void setCID(long CID){_CID=CID;}
bool operator==(const Borrow& b);
int Late(time_t _Current_date);//checking if borrow is late
void setStartDate(time_t addition){_StartDate+=addition;}
};
#endif
| [
"[email protected]@b387bec4-7a92-a7d2-31ee-4c2c7b2d7c03",
"[email protected]"
] | [
[
[
1,
9
],
[
22,
22
],
[
24,
30
],
[
34,
34
]
],
[
[
10,
21
],
[
23,
23
],
[
31,
33
],
[
35,
38
]
]
] |
08d01282a3116aff206ee7f590147abb00c77a28 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SESystem/SEAssert.h | 8342d012b34929cb4ea30797690aa3c5103fbfc0 | [] | no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,840 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_Assert_H
#define Swing_Assert_H
#ifdef NDEBUG
//----------------------------------------------------------------------------
#define SE_ASSERT(ignore) \
((void)0)
//----------------------------------------------------------------------------
#else
//----------------------------------------------------------------------------
// Microsoft Windows 2000/XP platform
//----------------------------------------------------------------------------
#if defined(_WIN32)
//----------------------------------------------------------------------------
#define SE_SAFEBREAKPOINT \
try \
{ \
_asm \
{ \
int 3 \
}; \
} \
catch(...) \
{ \
; \
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Macintosh OS X platform
//----------------------------------------------------------------------------
#elif defined(__APPLE__)
#define SE_SAFEBREAKPOINT ((void)0)
//----------------------------------------------------------------------------
// Linux platform
//----------------------------------------------------------------------------
#else
#define SE_SAFEBREAKPOINT ((void)0)
#endif
//----------------------------------------------------------------------------
#define SE_ASSERT(expr) \
if( !(expr) ) \
{ \
FILE* pFile = SESystem::SE_Fopen("Assert.txt", "at"); \
SESystem::SE_Fprintf(pFile, "SwingEngine assert:\n"); \
SESystem::SE_Fprintf(pFile, "File: %s\n", __FILE__); \
SESystem::SE_Fprintf(pFile, "Line: %d\n", __LINE__); \
SESystem::SE_Fprintf(pFile, "Function: %s\n", __FUNCTION__); \
SESystem::SE_Fclose(pFile); \
SE_SAFEBREAKPOINT; \
assert(expr); \
}
//----------------------------------------------------------------------------
#endif
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
87
]
]
] |
49537b9b1b95d606da436563500da73b91b601ac | 584d088c264ac58050ed0757b08d032b6c7fc83b | /wallChanger/wallChanger/XTabCtrl.h | 56c4c210cae540d6b98db2b1d95b705fd159c1ed | [] | no_license | littlewingsoft/lunaproject | a843ca37c04bdc4e1e4e706381043def1789ab39 | 9102a39deaad74b2d73ee0ec3354f37f6f85702f | refs/heads/master | 2020-05-30T15:21:20.515967 | 2011-02-04T18:41:43 | 2011-02-04T18:41:43 | 32,302,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,188 | h | #if !defined(AFX_XTABCTRL_H__A11951B3_2F95_11D3_A896_00A0C9B6FB28__INCLUDED_)
#define AFX_XTABCTRL_H__A11951B3_2F95_11D3_A896_00A0C9B6FB28__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// XTabCtrl.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CXTabCtrl window
#include <afxtempl.h>
class CXTabCtrl : public CTabCtrl
{
// Construction
public:
CXTabCtrl();
// Attributes
public:
// Operations
public:
void AddTab(CWnd* pWnd, LPTSTR lpszCaption, int iImage =0);
void EnableTab(int iIndex, BOOL bEnable = TRUE);
BOOL SelectTab(int iIndex);
void DeleteAllTabs();
void DeleteTab(int iIndex);
void SetTopLeftCorner(CPoint pt);
BOOL IsTabEnabled(int iIndex);
void SetDisabledColor(COLORREF cr);
void SetSelectedColor(COLORREF cr);
void SetNormalColor(COLORREF cr);
void SetMouseOverColor(COLORREF cr);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CXTabCtrl)
protected:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CXTabCtrl();
// Generated message map functions
protected:
CArray<BOOL, BOOL> m_arrayStatusTab; //** enabled Y\N
int m_iSelectedTab;
POINT m_ptTabs;
COLORREF m_crSelected;
COLORREF m_crDisabled;
COLORREF m_crNormal;
COLORREF m_crMouseOver;
int m_iIndexMouseOver;
bool m_bMouseOver;
bool m_bColorMouseOver;
bool m_bColorNormal;
bool m_bColorDisabled;
bool m_bColorSelected;
//{{AFX_MSG(CXTabCtrl)
afx_msg void OnSelchange(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnSelchanging(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnTimer(UINT nIDEvent);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_XTABCTRL_H__A11951B3_2F95_11D3_A896_00A0C9B6FB28__INCLUDED_)
| [
"jungmoona@2e9c511a-93cf-11dd-bb0a-adccfa6872b9"
] | [
[
[
1,
83
]
]
] |
740f956efa19bbf32e6fa2e80f33cb4d0adbf1e8 | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/IniWriter.cpp | 348886675d1fbbbe66615748db5804fcb4fc8041 | [] | no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,558 | cpp | #include "IniWriter.h"
using namespace std;
namespace IO{
IniWriter::IniWriter()
{
}
IniWriter::~IniWriter()
{
if (m_Path != "")
Close();
}
void IniWriter::Open(const std::string& path)
{
m_Path = path;
m_Data.clear();
}
void IniWriter::WriteInt(const std::tstring& root, const std::tstring& node, int i)
{
tstringstream str;
str << i;
WriteString(root, node, str.str());
}
void IniWriter::WriteFloat(const std::tstring& root, const std::tstring& node, float f)
{
tstringstream str;
str << f;
WriteString(root, node, str.str());
}
void IniWriter::WriteString(const std::tstring& root, const std::tstring& node, const tstring& str)
{
m_Data[root].push_back(make_pair(node, str));
}
bool IniWriter::Close()
{
tofstream stream(m_Path.c_str());
m_Path = "";
if (stream.is_open())
{
for_each(m_Data.cbegin(), m_Data.cend(), [&stream](const pair<tstring, vector<pair<tstring, tstring>>>& root)
{
stream << "[" << root.first << "]" << "\n";
tofstream& innerstream = stream; //nested lambda loses scope --> workaround
for_each(root.second.cbegin(), root.second.cend(), [&innerstream](const pair<tstring, tstring>& node)
{
innerstream << node.first << " = " << node.second << "\n";
});
stream << "\n";
});
stream.close();
return true;
}
else
{
return false;
}
}
} //end namespace
| [
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
] | [
[
[
1,
64
]
]
] |
0d1d7e038a39aa85eddfbbf5e28412e1efe62d91 | 6397eabfb8610d3b56c49f7d61bfc6f8636e6e09 | /classes/VideoCall.cpp | 6574a9027bdf3abfaf27561b54e73e1ee60efd8b | [] | no_license | ForjaOMF/OMF-WindowsMFCSDK | 947638d047f352ec958623a03d6ab470eae9cedd | cb6e6d1b6b90f91cb3668bc2bc831119b38b0011 | refs/heads/master | 2020-04-06T06:40:54.080051 | 2009-10-27T12:22:40 | 2009-10-27T12:22:40 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 17,782 | cpp | // VideoCall.cpp: archivo de implementación
//
#include "stdafx.h"
#include "VideoCall.h"
#include "SIPSocket.h"
#include "Frame263.h"
#include "WriteAvi.h"
#include "MD5Checksum.h"
#include "decoder\tmndec.h"
CVideoCall::CVideoCall(CString csStartTime, CString csFrom, CString csLocalIP, CString csPath, CString csCallId, CString csBranch, CString csFromTag, int nToTag)
{
m_csStartTime=csStartTime;
m_csFrom=csFrom;
m_csLocalIP=csLocalIP;
m_csPath=csPath;
m_csCallId=csCallId;
m_csBranch=csBranch;
m_csFromTag=csFromTag;
m_nToTag=nToTag;
m_pSocketAudio=NULL;
m_pSocketAudioCtrl=NULL;
m_pSocketVideo=NULL;
m_pSocketVideoCtrl=NULL;
m_bVideoReceived=true;
}
CVideoCall::~CVideoCall()
{
if(m_pSocketAudio)
{
m_pSocketAudio->Close();
delete m_pSocketAudio;
m_pSocketAudio=NULL;
}
if(m_pSocketAudioCtrl)
{
m_pSocketAudioCtrl->Close();
delete m_pSocketAudioCtrl;
m_pSocketAudioCtrl=NULL;
}
if(m_pSocketVideo)
{
m_pSocketVideo->Close();
delete m_pSocketVideo;
m_pSocketVideo=NULL;
}
if(m_pSocketVideoCtrl)
{
m_pSocketVideoCtrl->Close();
delete m_pSocketVideoCtrl;
m_pSocketVideoCtrl=NULL;
}
}
void CVideoCall::CreateSockets()
{
bool bRes;
CString csAddr;
m_pSocketAudio=new CSIPSocket(OnEventAudio,(DWORD)this);
bRes=m_pSocketAudio->Create(0,SOCK_DGRAM,FD_READ|FD_WRITE,m_csLocalIP);
m_pSocketAudio->GetSockNameEx(csAddr,m_nLocalAudioPort);
m_pSocketAudioCtrl=new CSIPSocket(OnEventAudioCtrl,(DWORD)this);
bRes=m_pSocketAudioCtrl->Create(m_nLocalAudioPort+1,SOCK_DGRAM,FD_READ|FD_WRITE,m_csLocalIP);
m_pSocketVideo=new CSIPSocket(OnEventVideo,(DWORD)this);
bRes=m_pSocketVideo->Create(0,SOCK_DGRAM,FD_READ|FD_WRITE,m_csLocalIP);
m_pSocketVideo->GetSockNameEx(csAddr,m_nLocalVideoPort);
m_pSocketVideoCtrl=new CSIPSocket(OnEventVideoCtrl,(DWORD)this);
bRes=m_pSocketVideoCtrl->Create(m_nLocalVideoPort+1,SOCK_DGRAM,FD_READ|FD_WRITE,m_csLocalIP);
}
void CVideoCall::SendMultimediaData(CString csAckData)
{
CString csPortAudio;
int nPosAudio=csAckData.Find("m=audio");
if(nPosAudio!=-1)
{
int nPosAudioEnd=csAckData.Find("RTP",nPosAudio+7);
if(nPosAudioEnd!=-1)
{
csPortAudio=csAckData.Mid(nPosAudio+7,nPosAudioEnd-nPosAudio-7);
csPortAudio.TrimLeft();
csPortAudio.TrimRight();
}
}
CString csPortVideo;
int nPosVideo=csAckData.Find("m=video");
if(nPosVideo!=-1)
{
int nPosVideoEnd=csAckData.Find("RTP",nPosVideo+7);
if(nPosVideoEnd!=-1)
{
csPortVideo=csAckData.Mid(nPosVideo+7,nPosVideoEnd-nPosVideo-7);
csPortVideo.TrimLeft();
csPortVideo.TrimRight();
}
}
if( (csPortAudio.IsEmpty()) || (csPortVideo.IsEmpty()) )
return;
m_nPortAudio=atoi(csPortAudio);
m_nPortVideo=atoi(csPortVideo);
// Audio Control
BYTE pDataAudio[44]={0x80, 0xc9, 0x00, 0x01, 0x52, 0xb1, 0x9e, 0xd0,
0x81, 0xca, 0x00, 0x06, 0x52, 0xb1, 0x9e, 0xd0,
0x01, 0x0e, 0x46, 0x72, 0x61, 0x6e, 0x5f, 0x6d,
0x40, 0x46, 0x72, 0x61, 0x6e, 0x5f, 0x6d, 0x31,
0x00, 0x00, 0x00, 0x00, 0x81, 0xcb, 0x00, 0x01,
0x52, 0xb1, 0x9e, 0xd0};
if(m_pSocketAudioCtrl)
m_pSocketAudioCtrl->SendTo(pDataAudio,44,m_nPortAudio+1,"195.76.180.160");
// VideoControl
BYTE pDataVideo[44]={0x80, 0xc9, 0x00, 0x01, 0x73, 0xaa, 0xdf, 0xe2,
0x81, 0xca, 0x00, 0x06, 0x52, 0xb1, 0x9e, 0xd0,
0x01, 0x0e, 0x46, 0x72, 0x61, 0x6e, 0x5f, 0x6d,
0x40, 0x46, 0x72, 0x61, 0x6e, 0x5f, 0x6d, 0x31,
0x00, 0x00, 0x00, 0x00, 0x81, 0xcb, 0x00, 0x01,
0x73, 0xaa, 0xdf, 0xe2};
if(m_pSocketVideoCtrl)
m_pSocketVideoCtrl->SendTo(pDataVideo,44,m_nPortVideo+1,"195.76.180.160");
// Audio
BYTE pDataAudioData[12]={0x80, 0x80, 0x04, 0xae, 0xbd, 0xb7, 0xc1, 0x40,
0x52, 0xb1, 0x9e, 0xd0};
if(m_pSocketAudio)
m_pSocketAudio->SendTo(pDataAudioData,12,m_nPortAudio,"195.76.180.160");
// Video
BYTE pDataVideoData[21]={0x80, 0x22, 0x8e, 0x9c, 0xef, 0xdb, 0xaf, 0x08,
0x73, 0xaa, 0xdf, 0xe2, 0x00, 0x40, 0x00, 0x00,
0x00, 0x80, 0x02, 0x08, 0x08};
if(m_pSocketVideo)
m_pSocketVideo->SendTo(pDataVideoData,21,m_nPortVideo,"195.76.180.160");
}
void CVideoCall::Echo(char* pBufData,DWORD dwLenData)
{
if(m_pSocketAudio)
m_pSocketAudio->SendTo(pBufData,dwLenData,m_nPortAudio,"195.76.180.160");
}
void CVideoCall::SaveAudioData(char* pBufData,DWORD dwLenData)
{
if(!m_bVideoReceived)
return;
CFile fl;
BOOL bRes=fl.Open(m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".raw",CFile::modeWrite);
if(!bRes)
bRes=fl.Open(m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".raw",CFile::modeWrite|CFile::modeCreate);
if(bRes)
{
fl.SeekToEnd();
fl.Write(pBufData,dwLenData);
fl.Close();
}
}
void CVideoCall::OnEventAudio(DWORD dwCookie,UINT nCode,char* pBufData,DWORD dwLenData,int nErrorCode)
{
if(nCode==FSOCK_RECEIVE)
{
CVideoCall* pThis=(CVideoCall*)dwCookie;
//pThis->Echo(pBufData,dwLenData);
BYTE btPayload=pBufData[1]&0x7f;
if(dwLenData>12)
{
if(btPayload==0)
{
BYTE* pRes=NULL;
pRes = (BYTE*)malloc((dwLenData-12) * 2);
pThis->DecodeULaw((BYTE*)&pBufData[12],dwLenData-12,pRes);
pThis->SaveAudioData((char*)pRes,(dwLenData-12)*2);
free(pRes);
}
else if(btPayload==8)
{
BYTE* pRes=NULL;
pRes = (BYTE*)malloc((dwLenData-12) * 2);
pThis->DecodeALaw((BYTE*)&pBufData[12],dwLenData-12,pRes);
pThis->SaveAudioData((char*)pRes,(dwLenData-12)*2);
free(pRes);
}
}
}
}
void CVideoCall::OnEventAudioCtrl(DWORD dwCookie,UINT nCode,char* pBufData,DWORD dwLenData,int nErrorCode)
{
int i=0;
}
void CVideoCall::Mirror(char* pBufData,DWORD dwLenData)
{
if(m_pSocketVideo)
m_pSocketVideo->SendTo(pBufData,dwLenData,m_nPortVideo,"195.76.180.160");
}
void CVideoCall::SaveVideoData(char* pBufData,DWORD dwLenData)
{
m_bVideoReceived=true;
CFile fl;
BOOL bRes=fl.Open(m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".263",CFile::modeWrite);
if(!bRes)
bRes=fl.Open(m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".263",CFile::modeWrite|CFile::modeCreate);
if(bRes)
{
fl.SeekToEnd();
fl.Write(pBufData,dwLenData);
fl.Close();
}
}
void CVideoCall::OnEventVideo(DWORD dwCookie,UINT nCode,char* pBufData,DWORD dwLenData,int nErrorCode)
{
if(nCode==FSOCK_RECEIVE)
{
CVideoCall* pThis=(CVideoCall*)dwCookie;
pThis->SaveVideoData(pBufData,dwLenData);
//pThis->Mirror(pBufData,dwLenData);
}
}
void CVideoCall::OnEventVideoCtrl(DWORD dwCookie,UINT nCode,char* pBufData,DWORD dwLenData,int nErrorCode)
{
int i=0;
}
void CVideoCall::Terminate()
{
// Audio Control
BYTE pDataAudio[44]={0x80, 0xc9, 0x00, 0x01, 0x52, 0xb1, 0x9e, 0xd0,
0x81, 0xca, 0x00, 0x06, 0x52, 0xb1, 0x9e, 0xd0,
0x01, 0x0e, 0x53, 0x49, 0x50, 0x54, 0x53, 0x54,
0x40, 0x53, 0x49, 0x50, 0x54, 0x53, 0x54, 0x31,
0x00, 0x00, 0x00, 0x00, 0x81, 0xcb, 0x00, 0x01,
0x52, 0xb1, 0x9e, 0xd0};
if(m_pSocketAudioCtrl)
m_pSocketAudioCtrl->SendTo(pDataAudio,44,m_nPortAudio+1,"195.76.180.160");
// VideoControl
BYTE pDataVideo[44]={0x80, 0xc9, 0x00, 0x01, 0x73, 0xaa, 0xdf, 0xe2,
0x81, 0xca, 0x00, 0x06, 0x52, 0xb1, 0x9e, 0xd0,
0x01, 0x0e, 0x53, 0x49, 0x50, 0x54, 0x53, 0x54,
0x40, 0x53, 0x49, 0x50, 0x54, 0x53, 0x54, 0x31,
0x00, 0x00, 0x00, 0x00, 0x81, 0xcb, 0x00, 0x01,
0x73, 0xaa, 0xdf, 0xe2};
if(m_pSocketVideoCtrl)
m_pSocketVideoCtrl->SendTo(pDataVideo,44,m_nPortVideo+1,"195.76.180.160");
if(m_pSocketAudio)
{
m_pSocketAudio->Close();
delete m_pSocketAudio;
m_pSocketAudio=NULL;
}
if(m_pSocketAudioCtrl)
{
m_pSocketAudioCtrl->Close();
delete m_pSocketAudioCtrl;
m_pSocketAudioCtrl=NULL;
}
if(m_pSocketVideo)
{
m_pSocketVideo->Close();
delete m_pSocketVideo;
m_pSocketVideo=NULL;
}
if(m_pSocketVideoCtrl)
{
m_pSocketVideoCtrl->Close();
delete m_pSocketVideoCtrl;
m_pSocketVideoCtrl=NULL;
}
DWORD dwDuration=ExportAudio();
ExportVideo(dwDuration);
}
void CVideoCall::DecodeALaw(BYTE* pData, DWORD dwLen, BYTE* pRes)
{
short pcm_A2lin[256] = {
-5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064,
-7808, -6528, -6272, -7040, -6784, -2752, -2624, -3008, -2880, -2240, -2112,
-2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,-22016,
-20992,-24064,-23040,-17920,-16896,-19968,-18944,-30208,-29184,-32256,-31232,
-26112,-25088,-28160,-27136,-11008,-10496,-12032,-11520, -8960, -8448, -9984,
-9472,-15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568, -344, -328,
-376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408,
-392, -440, -424, -88, -72, -120, -104, -24, -8, -56, -40,
-216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504,
-1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568,
-1760, -1696, -688, -656, -752, -720, -560, -528, -624, -592, -944,
-912, -1008, -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760,
4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040,
6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648,
4032, 3904, 3264, 3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920,
16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128,
15616, 13056, 12544, 14080, 13568, 344, 328, 376, 360, 280, 264,
312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88,
72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232,
152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248,
1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688, 656,
752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816,
784, 880, 848 };
for (int i = 0; i < dwLen; i++)
{
//First byte is the less significant byte
pRes[2 * i] = (BYTE)(pcm_A2lin[pData[i]] & 0xff);
//Second byte is the more significant byte
pRes[2 * i + 1] = (BYTE)(pcm_A2lin[pData[i]] >> 8);
}
}
void CVideoCall::DecodeULaw(BYTE* pData, DWORD dwLen, BYTE* pRes)
{
short pcm_u2lin[256] = {
-32124,-31100,-30076,-29052,-28028,-27004,-25980,-24956,-23932,-22908,-21884,
-20860,-19836,-18812,-17788,-16764,-15996,-15484,-14972,-14460,-13948,-13436,
-12924,-12412,-11900,-11388,-10876,-10364, -9852, -9340, -8828, -8316, -7932,
-7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116,
-4860, -4604, -4348, -4092, -3900, -3772, -3644, -3516, -3388, -3260, -3132,
-3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884, -1820,
-1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116,
-1052, -988, -924, -876, -844, -812, -780, -748, -716, -684, -652,
-620, -588, -556, -524, -492, -460, -428, -396, -372, -356, -340,
-324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164,
-148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56,
-48, -40, -32, -24, -16, -8, 0, 32124, 31100, 30076, 29052,
28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788,
16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388,
10876, 10364, 9852, 9340, 8828, 8316, 7932, 7676, 7420, 7164, 6908,
6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092,
3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620,
2492, 2364, 2236, 2108, 1980, 1884, 1820, 1756, 1692, 1628, 1564,
1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876,
844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524,
492, 460, 428, 396, 372, 356, 340, 324, 308, 292, 276,
260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112,
104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24,
16, 8, 0};
for (int i = 0; i < dwLen; i++)
{
//First byte is the less significant byte
pRes[2 * i] = (BYTE)(pcm_u2lin[pData[i]] & 0xff);
//Second byte is the more significant byte
pRes[2 * i + 1] = (BYTE)(pcm_u2lin[pData[i]] >> 8);
}
}
DWORD CVideoCall::ExportAudio()
{
CString csFile=m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".raw";
CFile fl;
BOOL bRes=fl.Open(csFile,CFile::modeRead);
if(bRes)
{
size_t flsize=fl.GetLength();
BYTE* pBuffer=(BYTE*)malloc(flsize);
fl.Read(pBuffer,flsize);
fl.Close();
CString csFileSave=m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".wav";
CFile fl2;
BOOL bRes2=fl2.Open(csFileSave,CFile::modeWrite|CFile::modeCreate);
if(bRes2)
{
BYTE strHead[]={0x52, 0x49, 0x46, 0x46, 0xA4, 0x95, 0x08, 0x00,
0x57, 0x41, 0x56, 0x45, 0x66, 0x6D, 0x74, 0x20,
0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
0x40, 0x1F, 0x00, 0x00, 0x80, 0x3E, 0x00, 0x00,
0x02, 0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61};
fl2.Write(strHead,40);
fl2.Write(&flsize,4);
fl2.Write(pBuffer,flsize);
fl2.Close();
try { CFile::Remove(csFile); }
catch(CFileException) {}
}
free(pBuffer);
return (DWORD)(flsize/16);
}
return 0;
}
void CVideoCall::InsertFrame(CObList& olFrames, CFrame263* pFrame, DWORD& dwPreviousFrame)
{
if( (pFrame->GetFrameNumber()>dwPreviousFrame) || (dwPreviousFrame==0) )
{
pFrame->SetTimerValue( (pFrame->GetFrameNumber()-dwPreviousFrame) * 30 );
olFrames.AddTail(pFrame);
dwPreviousFrame=pFrame->GetFrameNumber();
}
else if(dwPreviousFrame!=0)
{
pFrame->SetTimerValue( pFrame->GetFrameNumber() * 30 );
olFrames.AddTail(pFrame);
dwPreviousFrame=pFrame->GetFrameNumber();
}
else
delete pFrame;
}
void CVideoCall::RenderFrame(BYTE* pDecodedFrame, CFrame263* pFrame, DWORD dwFileSize, BYTE* pVideoBuffer)
{
if(pFrame->GetDecoded())
{
memcpy(pDecodedFrame,pFrame->GetDecoded(),pFrame->GetDecodedSize());
}
else
{
DWORD dwSize=dwFileSize-(pFrame->GetBuffer()-pVideoBuffer);
int nRet;
pFrame->GetBuffer()[0]=0;
nRet=DecompressFrame(pFrame->GetBuffer(),pFrame->GetBufferSize(),pDecodedFrame,80000,0);
pFrame->SetDecoded(pDecodedFrame,80000);
}
}
void CVideoCall::ExportVideo(DWORD dwAudioDuration)
{
CString csFile=m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".263";
CFile fl;
size_t flsize=0;
BYTE* pBuffer=NULL;
BOOL bRes=fl.Open(csFile,CFile::modeRead);
if(!bRes)
return;
CObList olFrames;
flsize=fl.GetLength();
pBuffer=(BYTE*)malloc(flsize);
fl.Read(pBuffer,flsize);
fl.Close();
DWORD dwValue;
DWORD dwPosFirst=0;
if(!flsize)
{
free(pBuffer);
return;
}
DWORD dwPreviousFrame=0;
DWORD dwDuration=0;
for(DWORD dwPos=0;dwPos<flsize-3;dwPos++)
{
dwValue=pBuffer[dwPos];
dwValue<<=8;
dwValue+=pBuffer[dwPos+1];
dwValue<<=8;
dwValue+=pBuffer[dwPos+2];
dwValue>>=2;
if(dwValue==0x20)
{
if(!dwPosFirst)
dwPosFirst=dwPos;
CFrame263* pFrame=new CFrame263(&pBuffer[dwPos],flsize-dwPos);
DWORD dwTime=pFrame->GetTimerValue();
if( (dwTime>0) && (dwTime<10000) )
dwDuration+=dwTime;
InsertFrame(olFrames, pFrame, dwPreviousFrame);
}
}
if(dwAudioDuration)
dwDuration=dwAudioDuration;
InitH263Decoder();
BYTE* pDecodedFrame=(BYTE*)malloc(80000);
CString csFileSave=m_csPath+"\\"+m_csStartTime+" "+m_csFrom+".avi";
CAVIFile oAviFile(csFileSave,176,144);
DWORD dwFrameMeanDuration=dwDuration/olFrames.GetCount();
oAviFile.SetFrameRate(1000/dwFrameMeanDuration);
CPaintDC dcMem(AfxGetMainWnd());
for(POSITION pos=olFrames.GetHeadPosition();pos;)
{
CFrame263* pFrame=(CFrame263*)olFrames.GetNext(pos);
RenderFrame(pDecodedFrame, pFrame, flsize, pBuffer);
BYTE* pDecoded=pFrame->GetDecoded();
CBitmap bmp;
bmp.CreateCompatibleBitmap(&dcMem,176,144);
CDC dcMemory;
dcMemory.CreateCompatibleDC(&dcMem);
dcMemory.SelectObject(&bmp);
if(pDecoded)
{
DWORD dwPos=0;
for(int i=0;i<144;i++)
{
for(int j=0;j<176;j++)
{
COLORREF clrPixel=RGB(pDecoded[dwPos],pDecoded[dwPos+1],pDecoded[dwPos+2]);
BYTE bRLeft=j?pDecoded[dwPos-3]:pDecoded[dwPos];
BYTE bRUp=i?pDecoded[dwPos-(3*176)]:pDecoded[dwPos];
BYTE bRRight=(j<175)?pDecoded[dwPos+3]:pDecoded[dwPos];
BYTE bRDown=(i<143)?pDecoded[dwPos+(3*176)]:pDecoded[dwPos];
BYTE bR=(bRLeft+bRUp+bRRight+bRDown)/4;
BYTE bGLeft=j?pDecoded[dwPos-3+1]:pDecoded[dwPos+1];
BYTE bGUp=i?pDecoded[dwPos-(3*176)+1]:pDecoded[dwPos+1];
BYTE bGRight=(j<175)?pDecoded[dwPos+3+1]:pDecoded[dwPos+1];
BYTE bGDown=(i<143)?pDecoded[dwPos+(3*176)+1]:pDecoded[dwPos+1];
BYTE bG=(bGLeft+bGUp+bGRight+bGDown)/4;
BYTE bBLeft=j?pDecoded[dwPos-3+2]:pDecoded[dwPos+2];
BYTE bBUp=i?pDecoded[dwPos-(3*176)+2]:pDecoded[dwPos+2];
BYTE bBRight=(j<175)?pDecoded[dwPos+3+2]:pDecoded[dwPos+2];
BYTE bBDown=(i<143)?pDecoded[dwPos+(3*176)+2]:pDecoded[dwPos+2];
BYTE bB=(bBLeft+bBUp+bBRight+bBDown)/4;
COLORREF clrPixelAntialiasing=RGB(bR,bG,bB);
dcMemory.SetPixel(j,i,clrPixelAntialiasing);
dwPos+=3;
}
}
}
dcMem.BitBlt(0,0,176,144,&dcMemory,0,0,SRCCOPY);
oAviFile.AddFrame(bmp);
}
try { CFile::Remove(csFile); }
catch(CFileException) {}
free(pDecodedFrame);
free(pBuffer);
}
| [
"[email protected]"
] | [
[
[
1,
568
]
]
] |
7d4654f1091bfc76dc99c81c7908e4de8289ec44 | 81e051c660949ac0e89d1e9cf286e1ade3eed16a | /quake3ce/code/botlib/l_memory.cpp | 99371f8231dbbcf7c11d1d54699db862b5c9130c | [] | no_license | crioux/q3ce | e89c3b60279ea187a2ebcf78dbe1e9f747a31d73 | 5e724f55940ac43cb25440a65f9e9e12220c9ada | refs/heads/master | 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,954 | cpp | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: l_memory.c
*
* desc: memory allocation
*
* $Archive: /MissionPack/code/botlib/l_memory.c $
*
*****************************************************************************/
#include"botlib_pch.h"
//#define MEMDEBUG
//#define MEMORYMANEGER
#define MEM_ID 0x12345678l
#define HUNK_ID 0x87654321l
int allocatedmemory;
int totalmemorysize;
int numblocks;
#ifdef MEMORYMANEGER
typedef struct memoryblock_s
{
unsigned long int id;
void *ptr;
int size;
#ifdef MEMDEBUG
char *label;
char *file;
int line;
#endif //MEMDEBUG
struct memoryblock_s *prev, *next;
} memoryblock_t;
memoryblock_t *memory;
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void LinkMemoryBlock(memoryblock_t *block)
{
block->prev = NULL;
block->next = memory;
if (memory) memory->prev = block;
memory = block;
} //end of the function LinkMemoryBlock
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void UnlinkMemoryBlock(memoryblock_t *block)
{
if (block->prev) block->prev->next = block->next;
else memory = block->next;
if (block->next) block->next->prev = block->prev;
} //end of the function UnlinkMemoryBlock
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
memoryblock_t *block;
assert(botimport.GetMemory); // bk001129 - was NULL'ed
ptr = botimport.GetMemory(size + sizeof(memoryblock_t));
block = (memoryblock_t *) ptr;
block->id = MEM_ID;
block->ptr = (char *) ptr + sizeof(memoryblock_t);
block->size = size + sizeof(memoryblock_t);
#ifdef MEMDEBUG
block->label = label;
block->file = file;
block->line = line;
#endif //MEMDEBUG
LinkMemoryBlock(block);
allocatedmemory += block->size;
totalmemorysize += block->size + sizeof(memoryblock_t);
numblocks++;
return block->ptr;
} //end of the function GetMemoryDebug
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetClearedMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
#ifdef MEMDEBUG
ptr = GetMemoryDebug(size, label, file, line);
#else
ptr = GetMemory(size);
#endif //MEMDEBUG
Com_Memset(ptr, 0, size);
return ptr;
} //end of the function GetClearedMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetHunkMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
memoryblock_t *block;
ptr = botimport.HunkAlloc(size + sizeof(memoryblock_t));
block = (memoryblock_t *) ptr;
block->id = HUNK_ID;
block->ptr = (char *) ptr + sizeof(memoryblock_t);
block->size = size + sizeof(memoryblock_t);
#ifdef MEMDEBUG
block->label = label;
block->file = file;
block->line = line;
#endif //MEMDEBUG
LinkMemoryBlock(block);
allocatedmemory += block->size;
totalmemorysize += block->size + sizeof(memoryblock_t);
numblocks++;
return block->ptr;
} //end of the function GetHunkMemoryDebug
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetClearedHunkMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
#ifdef MEMDEBUG
ptr = GetHunkMemoryDebug(size, label, file, line);
#else
ptr = GetHunkMemory(size);
#endif //MEMDEBUG
Com_Memset(ptr, 0, size);
return ptr;
} //end of the function GetClearedHunkMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
memoryblock_t *BlockFromPointer(void *ptr, char *str)
{
memoryblock_t *block;
if (!ptr)
{
#ifdef MEMDEBUG
//char *crash = (char *) NULL;
//crash[0] = 1;
botimport.Print(PRT_FATAL, "%s: NULL pointer\n", str);
#endif // MEMDEBUG
return NULL;
} //end if
block = (memoryblock_t *) ((char *) ptr - sizeof(memoryblock_t));
if (block->id != MEM_ID && block->id != HUNK_ID)
{
botimport.Print(PRT_FATAL, "%s: invalid memory block\n", str);
return NULL;
} //end if
if (block->ptr != ptr)
{
botimport.Print(PRT_FATAL, "%s: memory block pointer invalid\n", str);
return NULL;
} //end if
return block;
} //end of the function BlockFromPointer
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void FreeMemory(void *ptr)
{
memoryblock_t *block;
block = BlockFromPointer(ptr, "FreeMemory");
if (!block) return;
UnlinkMemoryBlock(block);
allocatedmemory -= block->size;
totalmemorysize -= block->size + sizeof(memoryblock_t);
numblocks--;
//
if (block->id == MEM_ID)
{
botimport.FreeMemory(block);
} //end if
} //end of the function FreeMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AvailableMemory(void)
{
return botimport.AvailableMemory();
} //end of the function AvailableMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int MemoryByteSize(void *ptr)
{
memoryblock_t *block;
block = BlockFromPointer(ptr, "MemoryByteSize");
if (!block) return 0;
return block->size;
} //end of the function MemoryByteSize
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void PrintUsedMemorySize(void)
{
botimport.Print(PRT_MESSAGE, "total allocated memory: %d KB\n", allocatedmemory >> 10);
botimport.Print(PRT_MESSAGE, "total botlib memory: %d KB\n", totalmemorysize >> 10);
botimport.Print(PRT_MESSAGE, "total memory blocks: %d\n", numblocks);
} //end of the function PrintUsedMemorySize
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void PrintMemoryLabels(void)
{
memoryblock_t *block;
int i;
PrintUsedMemorySize();
i = 0;
Log_Write("============= Botlib memory log ==============\r\n");
Log_Write("\r\n");
for (block = memory; block; block = block->next)
{
#ifdef MEMDEBUG
if (block->id == HUNK_ID)
{
Log_Write("%6d, hunk %p, %8d: %24s line %6d: %s\r\n", i, block->ptr, block->size, block->file, block->line, block->label);
} //end if
else
{
Log_Write("%6d, %p, %8d: %24s line %6d: %s\r\n", i, block->ptr, block->size, block->file, block->line, block->label);
} //end else
#endif //MEMDEBUG
i++;
} //end for
} //end of the function PrintMemoryLabels
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void DumpMemory(void)
{
memoryblock_t *block;
for (block = memory; block; block = memory)
{
FreeMemory(block->ptr);
} //end for
totalmemorysize = 0;
allocatedmemory = 0;
} //end of the function DumpMemory
#else
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
unsigned long int *memid;
ptr = botimport.GetMemory(size + sizeof(unsigned long int));
if (!ptr) return NULL;
memid = (unsigned long int *) ptr;
*memid = MEM_ID;
return (unsigned long int *) ((char *) ptr + sizeof(unsigned long int));
} //end of the function GetMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetClearedMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
#ifdef MEMDEBUG
ptr = GetMemoryDebug(size, label, file, line);
#else
ptr = GetMemory(size);
#endif //MEMDEBUG
Com_Memset(ptr, 0, size);
return ptr;
} //end of the function GetClearedMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetHunkMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
unsigned long int *memid;
ptr = botimport.HunkAlloc(size + sizeof(unsigned long int));
if (!ptr) return NULL;
memid = (unsigned long int *) ptr;
*memid = HUNK_ID;
return (unsigned long int *) ((char *) ptr + sizeof(unsigned long int));
} //end of the function GetHunkMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
#ifdef MEMDEBUG
void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line)
#else
void *GetClearedHunkMemory(unsigned long size)
#endif //MEMDEBUG
{
void *ptr;
#ifdef MEMDEBUG
ptr = GetHunkMemoryDebug(size, label, file, line);
#else
ptr = GetHunkMemory(size);
#endif //MEMDEBUG
Com_Memset(ptr, 0, size);
return ptr;
} //end of the function GetClearedHunkMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void FreeMemory(void *ptr)
{
unsigned long int *memid;
memid = (unsigned long int *) ((char *) ptr - sizeof(unsigned long int));
if (*memid == MEM_ID)
{
botimport.FreeMemory(memid);
} //end if
} //end of the function FreeMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AvailableMemory(void)
{
return botimport.AvailableMemory();
} //end of the function AvailableMemory
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void PrintUsedMemorySize(void)
{
} //end of the function PrintUsedMemorySize
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void PrintMemoryLabels(void)
{
} //end of the function PrintMemoryLabels
#endif
| [
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac"
] | [
[
[
1,
460
]
]
] |
e9f2e611f2e158b1432996f6d13a1b4898281748 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/test/mapped_file_test.cpp | 39e3d1caba17e7989f0b84a833b42d73280507f4 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,073 | cpp | // (C) Copyright Jonathan Turkanis 2004
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#include <fstream>
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "detail/temp_file.hpp"
#include "detail/verification.hpp"
using namespace std;
using namespace boost;
using namespace boost::iostreams;
using namespace boost::iostreams::test;
using boost::unit_test::test_suite;
// Code generation bugs cause tests to fail with global optimization.
#if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
# pragma optimize("g", off)
#endif
void mapped_file_test()
{
BOOST_MESSAGE("about to begin");
//--------------Reading from a mapped_file_source-------------------------//
{
// Note: the ifstream second is placed in a nested scope because
// closing and reopening a single ifstream failed for CW 9.4 on Windows.
// Test reading from a stream based on a mapped_file_source,
// in chars.
test_file test1, test2;
stream<mapped_file_source> first(test1.name());
{
ifstream second( test2.name().c_str(),
BOOST_IOS::in | BOOST_IOS::binary );
BOOST_CHECK_MESSAGE(
compare_streams_in_chars(first, second),
"failed reading from stream<mapped_file_source> in chars"
);
BOOST_MESSAGE(
"done reading from stream<mapped_file_source> in chars"
);
}
first.close();
// Test reading from a stream based on a mapped_file_source,
// in chunks. (Also tests reopening the stream.)
first.open(mapped_file_source(test1.name()));
{
ifstream second( test2.name().c_str(),
BOOST_IOS::in | BOOST_IOS::binary );
BOOST_CHECK_MESSAGE(
compare_streams_in_chunks(first, second),
"failed reading from stream<mapped_file_source> in chunks"
);
BOOST_MESSAGE(
"done reading from stream<mapped_file_source> in chunks"
);
}
}
//--------------Writing to a mapped_file_sink-----------------------------//
{
// Test writing to a stream based on a mapped_file_sink, in
// chars.
uppercase_file first, second; // Will overwrite these.
test_file test;
stream<mapped_file_sink> out;
out.open(mapped_file_sink(first.name()));
write_data_in_chars(out);
out.close();
BOOST_CHECK_MESSAGE(
compare_files(first.name(), test.name()),
"failed writing to stream<mapped_file_sink> in chars"
);
BOOST_MESSAGE(
"done writing to stream<mapped_file_source> in chars"
);
// Test writing to a stream based on a mapped_file_sink, in
// chunks. (Also tests reopening the stream.)
out.open(mapped_file_sink(second.name()));
write_data_in_chunks(out);
out.close();
BOOST_CHECK_MESSAGE(
compare_files(second.name(), test.name()),
"failed writing to stream<mapped_file_sink> in chunks"
);
BOOST_MESSAGE(
"done writing to stream<mapped_file_source> in chunks"
);
}
//--------------Writing to a newly created file-----------------------------//
{
// Test writing to a newly created mapped file.
temp_file first, second;
test_file test;
mapped_file_params p(first.name());
p.new_file_size = data_reps * data_length();
stream<mapped_file_sink> out;
out.open(mapped_file_sink(p));
write_data_in_chars(out);
out.close();
BOOST_CHECK_MESSAGE(
compare_files(first.name(), test.name()),
"failed writing to newly created mapped file in chars"
);
// Test writing to a newly created mapped file.
// (Also tests reopening the stream.)
p.path = second.name();
out.open(mapped_file_sink(p));
write_data_in_chunks(out);
out.close();
BOOST_CHECK_MESSAGE(
compare_files(second.name(), test.name()),
"failed writing to newly created mapped file in chunks"
);
}
//--------------Random access with a mapped_file--------------------------//
{
// Test reading, writing and seeking within a stream based on a
// mapped_file, in chars.
test_file test;
stream<mapped_file> io;
io.open(mapped_file(test.name()));
BOOST_CHECK_MESSAGE(
test_seekable_in_chars(io),
"failed seeking within stream<mapped_file> in chars"
);
BOOST_MESSAGE(
"done seeking within stream<mapped_file> in chars"
);
io.close();
// Test reading, writing and seeking within a stream based on a
// mapped_file, in chunks. (Also tests reopening the
// stream.)
io.open(mapped_file(test.name()));
BOOST_CHECK_MESSAGE(
test_seekable_in_chunks(io),
"failed seeking within stream<mapped_file> in chunks"
);
BOOST_MESSAGE(
"done seeking within stream<mapped_file> in chunks"
);
}
}
#if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
# pragma optimize("", on)
#endif
test_suite* init_unit_test_suite(int, char* [])
{
test_suite* test = BOOST_TEST_SUITE("mapped_file test");
test->add(BOOST_TEST_CASE(&mapped_file_test));
return test;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
183
]
]
] |
0be416d4b83ff4f77436ac6d0a9f1ed9453163da | 9b402d093b852a574dccb869fbe4bada1ef069c6 | /libs/mygui/inc/MyGUI_SubWidgetTextInterface.h | 93550921189d7268f823edc2640ee9c088b8e394 | [] | no_license | wangscript007/foundation-engine | adb24d4ccc932d7a8f8238170029de6d2db0cbfb | 2982b06d8f6b69c0654e0c90671aaef9cfc6cc40 | refs/heads/master | 2021-05-27T17:26:15.178095 | 2010-06-30T22:06:45 | 2010-06-30T22:06:45 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,372 | h | /*!
@file
@author Albert Semenov
@date 12/2007
@module
*/
#ifndef __MYGUI_SUB_WIDGET_TEXT_INTERFACE_H__
#define __MYGUI_SUB_WIDGET_TEXT_INTERFACE_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_CroppedRectangleInterface.h"
namespace MyGUI
{
class _MyGUIExport SubWidgetTextInterface : public CroppedRectangleInterface
{
public:
SubWidgetTextInterface(const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent) :
CroppedRectangleInterface(_coord, _align, _parent)
{}
// для каста сабскина
bool _isText() {return true;}
// работа с выделенным текстом
virtual size_t getSelectStart() {return 0;}
virtual size_t getSelectEnd() {return 0;}
virtual void setTextSelect(size_t _start, size_t _end) {}
// интенсивность выделенного текста
virtual bool getSelectBackground() {return true;}
virtual void setSelectBackground(bool _normal) {}
// управление видимостью курсора
virtual bool isCursorShow() {return false;}
virtual void setShowCursor(bool _show) {}
// управление положением курсора
virtual size_t getCursorPosition() {return 0;}
virtual void setCursorPosition(size_t _pos) {}
// возвращает положение курсора по произвольному положению
virtual size_t getCursorPosition(const IntPoint & _point) {return 0;}
// возвращает положение курсора в обсолютных координатах
virtual IntCoord getCursorCoord(size_t _position) {return IntCoord();}
// возвращает положение курсора в обсолютных координатах
inline IntPoint getCursorPoint(size_t _position)
{
const IntCoord & coord = getCursorCoord(_position);
return IntPoint(coord.left + coord.width / 2, coord.top + coord.height / 2);
}
// возвращает положение курсора в обсолютных координатах
inline IntRect getCursorRect(size_t _position)
{
const IntCoord & coord = getCursorCoord(_position);
return IntRect(coord.left, coord.top, coord.left + coord.width, coord.top + coord.height);
}
// возвращает размер текста в пикселях
virtual IntSize getTextSize() {return IntSize();}
// устанавливает смещение текста в пикселях
virtual void setViewOffset(IntPoint _point) {}
virtual IntPoint getViewOffset() {return IntPoint();}
virtual void setCaption(const Ogre::UTFString & _caption) {}
virtual const Ogre::UTFString & getCaption() {static Ogre::UTFString caption; return caption;}
virtual void setColour(const Ogre::ColourValue & _colour) {}
virtual const Ogre::ColourValue & getColour() {return Ogre::ColourValue::Black;}
virtual void setFontName(const Ogre::String & _font) {}
virtual const Ogre::String & getFontName() {static Ogre::String name; return name;}
virtual void setFontHeight(uint16 _height) {}
virtual uint16 getFontHeight() {return 0;}
virtual void setTextAlign(Align _align) {}
virtual Align getTextAlign() { return ALIGN_DEFAULT; }
};
} // namespace MyGUI
#endif // __MYGUI_SUB_WIDGET_TEXT_INTERFACE_H__
| [
"drivehappy@a5d1a9aa-f497-11dd-9d1a-b59b2e1864b6"
] | [
[
[
1,
89
]
]
] |
04d399303aa2a9a674a9db599c1e4fed83315772 | e03ee4538dce040fe16fc7bb48d495735ac324f4 | /Stable/InfluenceMaps/InfluenceMap.h | e6b0f45048f397e76f3ac3c87485d1b0d9533f3e | [] | no_license | vdelgadov/itcvideogame | dca6bcb084c5dde25ecf29ab1555dbe8b0a9a441 | 5eac60e901b29bff4d844f34cd52f97f4d1407b5 | refs/heads/master | 2020-05-16T23:43:48.956373 | 2009-12-01T02:09:08 | 2009-12-01T02:09:08 | 42,265,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,690 | h | #pragma once
#include <list>
#include <math.h>
//#include "../AIController/Actor.h"
#include "../AIController/AIController.h"
#include "../Main/Controller.h"
#include "../Main/Vector2D.h"
#include "../Main/Vector3D.h"
#include "../Main/CObjectMesh.cpp"
using namespace std;
class Actor;
class InfluenceMap {
private:
double **m_dMap;
double m_dWidth, m_dHEight;
list<CObjectMesh*> m_lActors;
int m_iMapWidth;
int m_iMapHeight;
public:
int getMapWidth(){
return this->m_iMapWidth;
}
int getMapHeight(){
return this->m_iMapHeight;
}
InfluenceMap(int map_width, int map_height, double width, double height){
this->m_dMap = new double*[map_height];
for(int i = 0; i<map_height; i++){
this->m_dMap[i] = new double[map_width];
for(int j=0; j<map_width; j++)
this->m_dMap[i][j] = 0;
}
this->m_iMapHeight = map_height;
this->m_iMapWidth = map_width;
this->m_dWidth = width;
this->m_dHEight = height;
}
void setActorList(list<CObjectMesh*> new_list){
this->m_lActors = new_list;
this->update();
}
void addActor(CObjectMesh* a){
this->m_lActors.push_back(a);
// this->update();
}
void mapCoords(Vector2D pos, int* map_x, int* map_y){
double x_interval = this->m_dWidth/this->m_iMapWidth;
double y_interval = this->m_dHEight/this->m_iMapHeight;
*map_x = int(pos.x / x_interval);
*map_y = int(pos.y / y_interval);
}
void mapCoords(Vector3D pos, int* map_x, int* map_z){
this->mapCoords(Vector2D(pos.x, pos.z), map_x, map_z);
}
void update(double time=0);
double getSpot(int r, int c){
return this->m_dMap[r][c];
}
};
| [
"leamsi.setroc@972b8bf6-92a2-11de-b72a-e7346c8bff7a",
"mrjackinc@972b8bf6-92a2-11de-b72a-e7346c8bff7a"
] | [
[
[
1,
12
],
[
14,
17
],
[
19,
25
],
[
27,
54
],
[
56,
59
],
[
61,
61
],
[
63,
84
]
],
[
[
13,
13
],
[
18,
18
],
[
26,
26
],
[
55,
55
],
[
60,
60
],
[
62,
62
]
]
] |
09ef97b6c2b989da48586ec85621f1b80dd0bfe0 | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/HovercraftUniverse/HovercraftRepresentation.h | 49f01fdf042fefc78b8806226fef451a3c794678 | [] | no_license | allenjacksonmaxplayio/uhasseltaacgua | 330a6f2751e1d6675d1cf484ea2db0a923c9cdd0 | ad54e9aa3ad841b8fc30682bd281c790a997478d | refs/heads/master | 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,153 | h | #ifndef HOVERCRAFTREPRESENTATION_H_
#define HOVERCRAFTREPRESENTATION_H_
#include "EntityRepresentation.h"
#include <vector>
#include <Moveable3DEmitter.h>
namespace HovUni {
class Hovercraft;
/**
* Representation of a hovercraft entity.
*
* @author Kristof Overdulve, Nick De Frangh, Dirk Delahaye
*/
class HovercraftRepresentation : public EntityRepresentation, public Moveable3DEmitter {
private:
static const float MAX_RPM;
static const float MIN_RPM;
/** The Particle Scene node, must be updated on every step */
Ogre::SceneNode* mParticleNode;
/** Animation state for rotation of hover */
Ogre::AnimationState * mRotorState;
/** Collision Sparks */
Ogre::ParticleSystem* mSparks;
Ogre::SceneNode* mSparksNode;
public:
/**
* Constructor.
*/
HovercraftRepresentation(Hovercraft * entity, Ogre::SceneManager * sceneMgr, Ogre::String meshFile, Ogre::String resourceGroupName, bool visible, bool castShadows,
Ogre::Real renderingDistance, Ogre::String materialFile, std::vector<Ogre::String> subMaterials, Ogre::SceneNode * node = 0);
/**
* Destructor.
*/
~HovercraftRepresentation();
/**
* Draws the representation.
*
* @param time since last frame
*/
void draw( Ogre::Real timeSinceLastFrame );
/**
* This function will be called every cycle to get updates for the position,
* velocity and orientation. This is needed to calculate the 3D sound in a
* realistic way.
*
* @param position Position in 3D space of the event. Specifying 0 / null will ignore this parameter.
* @param velocity Velocity in 'distance units per second' in 3D space of the event. See remarks.
* Specifying 0 / null will ignore this parameter
* @param orientation Orientation of the event sound cone.
* Only used if the event has a cone specified to determine cone detection, otherwise just
* specify 0 / null. Specifying 0 / null will ignore this parameter.
*/
virtual void getUpdates(Ogre::Vector3 ** position, Ogre::Vector3 ** velocity, Ogre::Vector3 ** orientation);
};
}
#endif | [
"kristof.overdulve@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
] | [
[
[
1,
6
],
[
10,
11
],
[
14,
16
],
[
18,
18
],
[
33,
43
],
[
65,
69
]
],
[
[
7,
9
],
[
20,
23
],
[
44,
44
],
[
52,
64
]
],
[
[
12,
13
],
[
26,
29
],
[
45,
51
]
],
[
[
17,
17
],
[
19,
19
],
[
24,
25
],
[
30,
32
]
]
] |
0a0b4bf4ef351bff246ed5c499d70ccf78657b0d | bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918 | /TPs CPOO/Gareth & Maxime/Projet/CanonNoir_Moteur_C++/fichiers/EtatCanonFin.h | a36d3aee1ff0d48064b7034bf0e8718a81f55e73 | [] | no_license | Issam-Engineer/tp4infoinsa | 3538644b40d19375b6bb25f030580004ed4a056d | 1576c31862ffbc048890e72a81efa11dba16338b | refs/heads/master | 2021-01-10T17:53:31.102683 | 2011-01-27T07:46:51 | 2011-01-27T07:46:51 | 55,446,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | h | /**
*\file EtatCanonFin.h
*\brief file which contains function declarations and attributes of the EtatCanonFin class
*\author Maxime HAVEZ
*\author Gareth THIVEUX
*\version 1.0
*/
#ifndef ETATCANONFIN_H
#define ETATCANONFIN_H
#include "EtatTir.h"
#include <math.h>
#define PI 3.141592653589793238
class EtatCanonFin : public Etat
{
private:
int puissance;
int angle;
public :
/**
*\fn EtatCanonFin(MoteurJeu * m)
*\brief Constructor
*/
EtatCanonFin(MoteurJeu * m);
/**
*\fn void execute()
*\brief Function which executes the current state
*/
void execute();
/**
*\fn virtual void init(int p, int a);
*\brief Function which initiates the shoot
*\param[in] int p : the power
*\param[in] int a : the angle
*/
virtual void init(int p, int a);
/**
*\fn bool tir()
*\brief function which calculates the tir
*\return a bool true if the bateau is touched
*/
bool tir();
/**
*\fn double z(double x)
*\brief return the result of a parabolic function
*\return y a double result of z function
*/
double z(double x);
};
inline void EtatCanonFin::init(int p,int a){puissance=p;angle=a;};
#endif
| [
"havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6",
"garethiveux@9f3b02c3-fd90-5378-97a3-836ae78947c6"
] | [
[
[
1,
1
],
[
7,
8
],
[
12,
33
],
[
35,
64
]
],
[
[
2,
6
],
[
9,
11
],
[
34,
34
],
[
65,
65
]
]
] |
29a0c739a255dda338e99ec1bbb43ff663b07b54 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /maxsdk2008/include/winutil.h | 416de0ae2e2ca322e8dfd1d2edc3d96d215b08be | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,039 | h | /**********************************************************************
*<
FILE: winutil.h
DESCRIPTION: Misc. windows related functions
CREATED BY: Rolf Berteig
HISTORY: 1-6-95 file created
*> Copyright (c) 1994-2003 All Rights Reserved.
**********************************************************************/
#ifndef __WINUTIL__
#define __WINUTIL__
#include "maxheap.h"
#include <limits>
#include <locale.h>
CoreExport float GetWindowFloat(HWND hwnd,BOOL *valid=NULL);
CoreExport int GetWindowInt(HWND hwnd,BOOL *valid=NULL);
CoreExport BOOL SetWindowTextInt( HWND hwnd, int i );
CoreExport BOOL SetWindowTextFloat( HWND hwnd, float f, int precision=3 );
CoreExport BOOL SetDlgItemFloat( HWND hwnd, int idControl, float val );
CoreExport float GetDlgItemFloat( HWND hwnd, int idControl, BOOL *valid=NULL );
CoreExport void SetDlgFont( HWND hDlg, HFONT hFont );
CoreExport void SlideWindow( HWND hwnd, int x, int y );
CoreExport void StretchWindow( HWND hwnd, int w, int h );
CoreExport BOOL CenterWindow(HWND hWndChild, HWND hWndParent);
CoreExport void GetClientRectP( HWND hwnd, Rect *rect );
CoreExport void DrawIconButton( HDC hdc, HBITMAP hBitmap, Rect& wrect, Rect& brect, BOOL in );
CoreExport int GetListHieght( HWND hList );
CoreExport void ShadedVertLine( HDC hdc, int x, int y0, int y1, BOOL in );
CoreExport void ShadedHorizLine( HDC hdc, int y, int x0, int x1, BOOL in );
CoreExport void ShadedRect( HDC hdc, RECT& rect );
CoreExport void Rect3D( HDC hdc, RECT& rect, BOOL in );
CoreExport void WhiteRect3D( HDC hdc, RECT rect, BOOL in );
CoreExport void DrawButton( HDC hdc, RECT rect, BOOL in );
CoreExport void XORDottedRect( HWND hwnd, IPoint2 p0, IPoint2 p1, int solidToRight = 0 );
CoreExport void XORDottedCircle( HWND hwnd, IPoint2 p0, IPoint2 p1, int solidToRight = 0 );
CoreExport void XORDottedPolyline( HWND hwnd, int count, IPoint2 *pts, int solid = 0);
CoreExport void XORRect(HDC hdc, RECT& r, int border=1);
CoreExport void MakeButton2State(HWND hCtrl);
CoreExport void MakeButton3State(HWND hCtrl);
CoreExport int GetCheckBox(HWND hw, int id);
// WIN64 Cleanup: Shuler
CoreExport void SetCheckBox(HWND hw, int id, BOOL b);
CoreExport BOOL DoesFileExist(const TCHAR *file);
CoreExport int GetBitsPerPixel();
// Delete superfluous zeroes from float string: 1.2300000 -> 1.23
CoreExport void StripTrailingZeros(TCHAR* buf);
template<class T> void LimitValue( T& value, T min, T max )
{
if ( value < min ) value = min;
if ( value > max ) value = max;
}
// mjm - 1.26.99 - safely casts double to float - valid flag will indicate overflow
inline float Dbl2Flt(double val, BOOL *valid = NULL)
{
if ( val < 0.0f )
{
if ( val < -FLT_MAX )
{
if (valid) *valid = FALSE;
return -FLT_MAX;
}
if ( val > -FLT_MIN )
{
if (valid) *valid = FALSE;
return -FLT_MIN;
}
if (valid) *valid = TRUE;
return (float)val;
}
if ( val > FLT_MAX )
{
if (valid) *valid = FALSE;
return FLT_MAX;
}
if ( val < FLT_MIN && val != 0.0 )
{
if (valid) *valid = FALSE;
return FLT_MIN;
}
if (valid) *valid = TRUE;
return (float)val;
}
// mjm - 1.26.99 - safely casts double to int - valid flag will indicate overflow
inline int Dbl2Int(double val, BOOL *valid = NULL)
{
if ( val > INT_MAX )
{
if (valid) *valid = FALSE;
return INT_MAX;
}
if ( val < INT_MIN )
{
if (valid) *valid = FALSE;
return INT_MIN;
}
if (valid) *valid = TRUE;
return (int)val;
}
#define MAKEPOINT( lparam, pt ) { pt.x = (short)LOWORD(lparam); pt.y = (short)HIWORD(lparam); }
// The following two functions extend list boxes. Set the list box to be
// owner draw and then call these two methods in response to the
// WM_MEASUREITEM and WM_DRAWITEM messages.
//
// Flags to pass to CustListDrawItem
#define CUSTLIST_DISABLED (1<<0) // Text is gray
#define CUSTLIST_MED_DISABLED (1<<1) // Test is darker gray
#define CUSTLIST_SEPARATOR (1<<2) // Draws a separator instead of text
#define CUSTLIST_DBL_SERPARATOR (1<<3) // Draw a double line seperator
#define CUSTLIST_RED (1<<4) // Text is red
CoreExport void CustListMeasureItem(HWND hList,WPARAM wParam, LPARAM lParam);
CoreExport void CustListDrawItem(HWND hList,WPARAM wParam, LPARAM lParam,DWORD flags);
// MAX extended message box functionality DB 7/98
#define MAX_MB_HOLD 0x0001 // add "Hold" button
#define MAX_MB_DONTSHOWAGAIN 0x0002 // add "Don't show this dialog again" checkbox
// The first four parameters are just like the Win32 MessageBox routine (but not
// all MessageBox functionality is supported!)
//
// The last two optional args add the functionality listed above -- exType is used
// for adding the additional buttons, and exRet is used for getting the extra
// return info. For example, if exType includes MAX_MB_DONTSHOWAGAIN, and exRet
// is non-NULL, then exRet will have MAX_MB_DONTSHOWAGAIN set if that checkbox was
// checked by the user.
CoreExport INT_PTR MaxMsgBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT type, UINT exType=0, DWORD *exRet=NULL);
// WIN64 Cleanup: Shuler
/**********************************************************************
*
* alpha blended icon support...
*
**********************************************************************/
#include "plugapi.h"
enum LoadMAXIconErrors
{
LMI_Ok,
LMI_ResourceNotFound,
LMI_ResourceLoadFailed,
LMI_ImageAndMaskNotCompatible,
};
CoreExport LoadMAXIconErrors LoadMAXIcon(HINSTANCE hInstance, LPCTSTR resID, LPCTSTR resMaskID, COLORREF bkColor,
HIMAGELIST imageList, int imageIndex, int preMultAlpha=TRUE);
// returns index of first image into existing imageList
CoreExport int LoadMAXIconFromBMI(LPBITMAPINFOHEADER biImage, LPBITMAPINFOHEADER biMask, COLORREF bkColor, TCHAR* pFilePrefix, int preMultAlpha=TRUE, HIMAGELIST* pImageList=NULL);
CoreExport BITMAPINFOHEADER *LoadBitmapFromFile(TCHAR *filename);
CoreExport void DrawMAXIcon(HDC hDC, Rect &r, HIMAGELIST hList32, HIMAGELIST hList16, int index);
// Compute a good color to use for drawing XOR lines over a particular background color
CoreExport COLORREF ComputeXORDrawColor(COLORREF bkgColor);
// Compute a good color to use for drawing XOR lines over a viewport
CoreExport COLORREF ComputeViewportXORDrawColor();
/**********************************************************************
Dialog resizing and positioning. A generic class for resizing a dialog.
Includes functions to save and restore the initial size and position
of the dialog.
This class makes it easy to add resizability to a dialog. You'll need
one instance of this class for each instance of a dialog. Set up
various parameters during your dialog's WM_INITDIALOG processing,
then let this class handle all WM_SIZE events.
Include library: core.lib
HOW TO USE THIS CLASS:
1. Create either a static instance in your DlgProc, or a live instance
in the object that is driving the dialog.
2. In your WM_INITDIALOG handling, call Initialize().
3. Optionally, call SetMinimumDlgSize(). However, the default minimum size
for a dialog is it's size at the time Initialize() is called.
4. For each control in your dialog, call SetControlInfo(); you only need
to do this if you want to override the default behavior for the control.
For most, the default is to be locked to the top left corner, with a
fixed size. Some controls may default to resizing; SysListView32 has
some specialized behaviors you may not need to override.
5. Process the WM_SIZING message, and call Process_WM_SIZING().
6. Process the WM_SIZE message, and call Process_WM_SIZE().
**********************************************************************/
class DialogItemSizeData: public MaxHeapOperators
{
public:
HWND hwnd;
RECT rect;
DWORD flags;
DialogItemSizeData(HWND h, DWORD f = 0)
: hwnd(h), flags(f)
{
WINDOWPLACEMENT wpControl;
wpControl.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(hwnd, &wpControl);
rect = wpControl.rcNormalPosition;
}
// Compiler-generated destructor, copy constructor, and assignment
// operator should all be fine.
private:
// Ensure no default constructor is generated or used.
DialogItemSizeData();
};
class DialogResizer: public MaxHeapOperators
{
public:
DialogResizer() : mhDlg(NULL)
{
mMinDlgSize.left = mMinDlgSize.top = 0;
mMinDlgSize.right = mMinDlgSize.bottom = 50;
mOriginalClientRect.left = mOriginalClientRect.top = 0;
mOriginalClientRect.right = mOriginalClientRect.bottom = 50;
}
// Compiler-generated destructor, copy constructor, and assignment
// operator should all be fine.
CoreExport void Initialize(HWND hDlg);
CoreExport void SetMinimumDlgSize(LONG wid, LONG ht);
// If you have a control you want to have fixed width and height, and locked to
// top left, you do not have to call SetControlInfo, as that is the default
// behavior.
enum PositionControl
{ kLockToTopLeft=1, kLockToTopRight, kLockToBottomLeft, kLockToBottomRight, kPositionsOnly=0xff };
enum ControlFlags
{ kDefaultBehavior=0, kWidthChangesWithDialog=1<<8, kHeightChangesWithDialog=1<<9 };
CoreExport void SetControlInfo(int resID, PositionControl pos, DWORD flags = kDefaultBehavior);
CoreExport void SetControlInfo(HWND hwnd, PositionControl pos, DWORD flags = kDefaultBehavior);
CoreExport void Process_WM_SIZING(WPARAM wParam, LPARAM lParam);
CoreExport void Process_WM_SIZE(WPARAM wParam, LPARAM lParam);
// Static methods to let you save and restore the size and position of your dialog
// (whether it's resizable or not).
// If the section name is not specified, it will default to
// [DialogResizer_SizeAndPositions].
// If the ini filename is not specified, it will default to the main application ini
// file, typically 3dsmax.ini.
CoreExport static void SaveDlgPosition(HWND hDlg, const TCHAR* keyname,
const TCHAR* section = NULL, const TCHAR* inifn = NULL);
CoreExport static void LoadDlgPosition(HWND hDlg, const TCHAR* keyname,
const TCHAR* section = NULL, const TCHAR* inifn = NULL);
friend static BOOL CALLBACK GetInitialPositionECP(HWND hwnd, LPARAM lParam);
private:
Tab<DialogItemSizeData> mControls;
RECT mMinDlgSize;
RECT mOriginalClientRect;
HWND mhDlg;
};
//! \brief MaxLocaleHandler handles Globalization
//! This is a helper class that switches the Locale settings to a temporary
//! value and restores the previous locale setting in the destructor.
//! To use this class simply instanciate a variable of it's class at the beginning
//! of a method. The given locale setting will be set until the method is left and
//! the destructor of the class is called automatically.
class MaxLocaleHandler: public MaxHeapOperators {
public:
//! \brief Constructor
//!
//! \param[in] category - The category affected by locale. See _tsetlocale in MSDN help for more info
//! \param[in] localeSetting - The locale name. See _tsetlocale in MSDN help for more info
MaxLocaleHandler(int category = LC_ALL, const MCHAR* localeSetting = _M("C"));
//! \brief Destructor, resets locale setting to original value
~MaxLocaleHandler();
//! \brief Resets locale setting to original value, before the object goes out of scope.
void RestoreLocale();
private:
int m_category;
MSTR m_oldLocale;
};
inline MaxLocaleHandler::MaxLocaleHandler(int category, const MCHAR* localeSetting)
: m_oldLocale(setlocale(category, NULL)), // Save old locale
m_category(category)
{
// Set new locale
setlocale(category, localeSetting);
}
inline MaxLocaleHandler::~MaxLocaleHandler() {
if( !m_oldLocale.isNull() )
{
// Restore old locale
setlocale(m_category, m_oldLocale.data());
}
}
inline void MaxLocaleHandler::RestoreLocale() {
if( !m_oldLocale.isNull() )
{
// Restore old locale
setlocale(m_category, m_oldLocale.data());
// Prevent double restores
m_oldLocale = _M("");
}
}
namespace MaxSDK
{
//! \brief Multiple character search for ComboBoxes
/*! This method will select an entry in the ComboBox based on the
multiple key entries over a set time period. The functionality mimics the
standard windows ListView behavior, including the documented one second
time period for key entries. It is intended to be used in conjunction with
the WM_CHAR message in the ComboBox's callback.
Example usage:
\code
case WM_CHAR:
return MaxSDK::SearchComboBox( hWnd, (TCHAR)wParam, _T(" "));
\endcode
\param[in] hWnd Window handle of ComboBox
\param[in] key Character entered by user
\param[in] szTrim Optional parameter. Default is NULL. Any leading characters in
the ComboBox entries that are contained in szTrim will be removed prior to
comparing to the search string.
\return true if match found, false if not
*/
CoreExport bool SearchComboBox( HWND hWnd, TCHAR key, const TCHAR* szTrim = NULL );
//! \brief Multiple character search for ListBoxes
/*! This method will select an entry in the ListBox based on the
multiple key entries over a set time period. The functionality mimics the
standard windows ListView behavior, including the documented one second
time period for key entries. It is intended to be used in conjunction with
the WM_CHAR message in the ListBox's callback.
Example usage:
\code
case WM_CHAR:
return MaxSDK::SearchListBox( hWnd, (TCHAR)wParam, _T(" "));
\endcode
\param[in] hWnd Window handle of ListBox
\param[in] key Character entered by user
\param[in] szTrim Optional parameter. Default is NULL. Any leading characters in
the ListBox entries that are contained in szTrim will be removed prior to
comparing to the search string.
\return true if match found, false if not
*/
CoreExport bool SearchListBox( HWND hWnd, TCHAR key, const TCHAR* szTrim = NULL );
};
#endif
| [
"[email protected]"
] | [
[
[
1,
380
]
]
] |
f0fb7656a6a0bd909bebecacc2ba8506df3a65dd | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/level/physics/ForceGenerator.h | 719b5088c7f1a9dd066ac19a20b1d76cbc18d230 | [] | no_license | galek/hesperus | 4eb10e05945c6134901cc677c991b74ce6c8ac1e | dabe7ce1bb65ac5aaad144933d0b395556c1adc4 | refs/heads/master | 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | h | /***
* hesperus: ForceGenerator.h
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#ifndef H_HESP_FORCEGENERATOR
#define H_HESP_FORCEGENERATOR
namespace hesp {
//#################### FORWARD DECLARATIONS ####################
class PhysicsObject;
class ForceGenerator
{
//#################### DESTRUCTOR ####################
public:
virtual ~ForceGenerator() {}
//#################### PUBLIC ABSTRACT METHODS ####################
public:
virtual void update_force(PhysicsObject& object) const = 0;
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
e8c9e3ffffe72eac5064a3e2bfa6070beaf73549 | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/gfx/vertex_writer.hxx | 4667d389ba943ff8f65acfe4fb83e25adbd75f22 | [] | no_license | wavs/pfe-2011-scia | 74e0fc04e30764ffd34ee7cee3866a26d1beb7e2 | a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a | refs/heads/master | 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,932 | hxx | #include "vertex_writer.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
template<class T>
VertexWriter<T>::VertexWriter()
: MIndex(NULL),
MIndexCount(0),
MVertex(NULL),
MVertexCount(0),
MIsInitialized(false),
MIndexStart(0)
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
template<class T>
VertexWriter<T>::~VertexWriter()
{
LOG_ASSERT(MIsInitialized == false);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
template<class T>
inline T& VertexWriter<T>::GetVertex(unsigned parIth)
{
LOG_ASSERT(MIsInitialized);
LOG_ASSERT(parIth < MVertexCount);
return MVertex[parIth];
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
template<class T>
inline void VertexWriter<T>::AddTriangle(unsigned parI1, unsigned parI2, unsigned parI3)
{
LOG_ASSERT(MIsInitialized);
LOG_ASSERT(MCurIndex < (MIndexCount - 2));
LOG_ASSERT(parI1 < MVertexCount &&
parI2 < MVertexCount &&
parI3 < MVertexCount);
MIndex[MCurIndex + 0] = MIndexStart + parI1;
MIndex[MCurIndex + 1] = MIndexStart + parI2;
MIndex[MCurIndex + 2] = MIndexStart + parI3;
MCurIndex += 3;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
template<class T>
inline void VertexWriter<T>::Finish()
{
LOG_ASSERT(MIsInitialized == true);
LOG_ASSERT(MCurIndex == MIndexCount);
MIsInitialized = false;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
template<class T>
inline void VertexWriter<T>::SetMemory(unsigned* parIndex,
unsigned parIndexCount,
T* parVertex,
unsigned parVertexCount,
unsigned parIndexStart)
{
LOG_ASSERT(MIsInitialized == false);
LOG_ASSERT(parVertexCount >= 3 && parIndexCount > 0);
MIndex = parIndex;
MIndexCount = parIndexCount;
MVertex = parVertex;
MVertexCount = parVertexCount;
MCurIndex = 0;
MIndexStart = parIndexStart;
MIsInitialized = true;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
] | [
[
[
1,
92
]
]
] |
08594b78cc2d64e7f799a07b2315ac3556a8c2f5 | c3ae23286c2e8268355241f8f06cd1309922a8d6 | /rateracerlib/LightSource.h | ac7a8ccf355a3e603ae544964b8b49ded83f9a59 | [] | no_license | BackupTheBerlios/rateracer-svn | 2f43f020ecdd8a3528880d474bec1c0464879597 | 838ad3f326962028ce8d493d2c06f6af6ea4664c | refs/heads/master | 2020-06-04T03:31:51.633612 | 2005-05-30T06:38:01 | 2005-05-30T06:38:01 | 40,800,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #pragma once
#include "mathlib.h"
// TODO: amb, diff, spec, attenuation
// TODO: spot light - direction, exponent, cutoffAngle, (inner + outer cone)
// TODO: (global ambient)
class LightSource
{
public:
LightSource( Vec3 Position = Vec3(0,0,0), Vec3 Color = Vec3(0.5f,0.5f,0.5f) )
{
position = Position;
color = Color;
}
virtual ~LightSource() {}
Vec3 position;
Vec3 color;
};
| [
"gweronimo@afd64b18-8dda-0310-837d-b02fe5df315d"
] | [
[
[
1,
22
]
]
] |
2874682df37b7629d28ff81192aa7b727305d3a3 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/branches/newton20/engine/core/src/PhysicalThing.cpp | 6f0096166e3b098ba42850983a36d34da0c8316c | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,129 | cpp | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* 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
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#include "stdinc.h" //precompiled header
#include "PhysicalThing.h"
#include "Actor.h"
#include "Exception.h"
#include "MathUtil.h"
#include "MeshObject.h"
#include "PhysicalObject.h"
using namespace Ogre;
using namespace OgreNewt;
using namespace OgreNewt::CollisionPrimitives;
namespace rl
{
PhysicalThing::PhysicalThing(
GeometryType geomType, PhysicalObject* po, Real mass, bool hullModifier)
:
mActor(NULL),
mBody(NULL),
mUpVectorJoint(NULL),
mPendingForce(Vector3::ZERO),
mOverrideGravity(false),
mGravity(Vector3::ZERO),
mContactListener(NULL),
mPoseCollisions(),
mGeometryType(geomType),
mPhysicalObject(po),
mMass(mass),
mHullModifier(hullModifier),
mPhysicsController(NULL)
{
}
PhysicalThing::~PhysicalThing()
{
mPoseCollisions.clear();
delete mBody;
mBody = NULL;
}
Ogre::Vector3 PhysicalThing::getPosition() const
{
Quaternion quat;
Vector3 pos;
mBody->getPositionOrientation(pos, quat);
return pos;
}
void PhysicalThing::setPosition(Real x, Real y, Real z)
{
setPosition(Vector3(x, y, z));
}
void PhysicalThing::setPosition(const Vector3& pos)
{
Quaternion quat;
Vector3 oldPos;
mBody->getPositionOrientation(oldPos, quat);
mBody->setPositionOrientation(pos, quat);
}
Ogre::Quaternion PhysicalThing::getOrientation() const
{
Quaternion quat;
Vector3 pos;
mBody->getPositionOrientation(pos, quat);
return quat;
}
void PhysicalThing::setOrientation(Real w, Real x, Real y, Real z)
{
setOrientation(Quaternion(w, x, y, z));
}
void PhysicalThing::setOrientation(const Quaternion& orientation)
{
Quaternion oldOrientation;
Vector3 pos;
mBody->getPositionOrientation(pos, oldOrientation);
mBody->setPositionOrientation(pos, orientation);
}
void PhysicalThing::setVelocity(const Vector3& vel)
{
mBody->setVelocity(vel);
}
Vector3 PhysicalThing::getVelocity()
{
return mBody->getVelocity();
}
Actor *PhysicalThing::getActor(void) const
{
return mActor;
}
OgreNewt::Body* PhysicalThing::_getBody() const
{
return mBody;
}
void PhysicalThing::setBody(OgreNewt::Body* body)
{
mBody = body;
mBody->setUserData(mActor);
}
void PhysicalThing::_update()
{
if (mBody && mActor)
{
mBody->setPositionOrientation(
mActor->_getSceneNode()->_getDerivedPosition(),
mActor->_getSceneNode()->_getDerivedOrientation());
mActor->_update(Actor::UF_ALL & ~Actor::UF_PHYSICAL_THING);
}
}
void PhysicalThing::_setActor(Actor* actor)
{
mActor = actor;
if (mBody != NULL)
mBody->setUserData(actor);
}
void PhysicalThing::_attachToSceneNode(Ogre::SceneNode* node)
{
mBody->attachNode(node);
}
void PhysicalThing::_attachToBone(MeshObject* object, const std::string& boneName )
{
//Entity* attachTarget = object->getEntity();
//Body* body = mGeometry->getBody();
//attachTarget->attachObjectToBone(boneName, body);
}
void PhysicalThing::_detachFromSceneNode(Ogre::SceneNode* node)
{
///\todo Wie implementieren?
}
void PhysicalThing::setUpConstraint(const Vector3& upVector)
{
if (!mUpVectorJoint)
{
mUpVectorJoint = new OgreNewt::BasicJoints::UpVector(
mBody->getWorld(), mBody, upVector);
}
else
{
mUpVectorJoint->setPin(upVector);
}
}
Ogre::Vector3 PhysicalThing::getUpConstraint() const
{
Vector3 rval = Vector3::ZERO;
if (mUpVectorJoint)
{
rval = mUpVectorJoint->getPin();
}
return rval;
}
void PhysicalThing::clearUpConstraint()
{
delete mUpVectorJoint;
mUpVectorJoint = NULL;
}
void PhysicalThing::onApplyForceAndTorque(float timestep)
{
Vector3 gravity = mOverrideGravity ?
mGravity : PhysicsManager::getSingleton().getGravity();
mBody->addForce(mPendingForce + gravity*getMass());
mPendingForce = Vector3::ZERO;
}
void PhysicalThing::addForce(const Ogre::Vector3& force)
{
mBody->unFreeze();
mPendingForce += force;
}
Ogre::Real PhysicalThing::getMass() const
{
return mMass;
}
void PhysicalThing::setMass(Ogre::Real mass)
{
Vector3 inertia;
mBody->getMassMatrix(mMass, inertia);
mMass = mass;
mBody->setMassMatrix(mass, inertia);
}
void PhysicalThing::setGravityOverride(bool override, const Vector3& gravity)
{
mOverrideGravity = override;
mGravity = mOverrideGravity ? gravity : Vector3::ZERO;
}
void PhysicalThing::setGravityOverride(bool override, Real x, Real y, Real z)
{
setGravityOverride(override, Vector3(x, y, z));
}
void PhysicalThing::updateCollisionHull()
{
Entity* entity = static_cast<Entity*>(mActor->_getMovableObject());
entity->_updateAnimation();
Node* node = entity->getParentNode();
RlAssert(node,
"Actor has to be placed in the scene in order to update its collision hull.");
Vector3 position;
Quaternion orientation;
mBody->getPositionOrientation(position, orientation);
if (mGeometryType == GT_CONVEXHULL)
{
Matrix4 transform = node->_getFullTransform().inverse();
std::vector<Vector3> vertices;
vertices.reserve(100);
bool sharedAdded = false;
// loop over subentities and retrieve vertex positions
size_t subentityCount = entity->getNumSubEntities();
for (size_t i = 0; i < subentityCount; ++i)
{
SubEntity* subEntity = entity->getSubEntity(i);
VertexData* vdata = 0;
if (subEntity->getSubMesh()->useSharedVertices && !sharedAdded)
{
vdata = entity->_getSkelAnimVertexData();
sharedAdded = true;
}
else if (!subEntity->getSubMesh()->useSharedVertices)
{
vdata = subEntity->_getSkelAnimVertexData();
}
if (vdata)
{
size_t vcount = vdata->vertexCount;
VertexDeclaration* vdecl = vdata->vertexDeclaration;
const VertexElement* velem = vdecl->findElementBySemantic( Ogre::VES_POSITION );
HardwareVertexBufferSharedPtr vbuffer =
vdata->vertexBufferBinding->getBuffer(velem->getSource());
unsigned char* vptr = static_cast<unsigned char*>(
vbuffer->lock(HardwareBuffer::HBL_READ_ONLY ));
//loop through vertex data...
size_t start = vdata->vertexStart;
for (size_t j = start; j < (start + vcount); ++j)
{
float* vpos;
//get offset to Position data!
unsigned char* offset = vptr + (j * vbuffer->getVertexSize());
velem->baseVertexPointerToElement(offset, &vpos);
Vector3 v = Vector3(vpos[0], vpos[1], vpos[2]);
//Positions in world space. So we need to transform them back.
vertices.push_back(transform * v);
offset++; // question: do we really need this here?
}
vbuffer->unlock();
}
}
CollisionPtr collision(new ConvexHull(PhysicsManager::getSingleton()._getNewtonWorld(),
&vertices[0], vertices.size()));
mBody->setCollision(collision);
}
else if (mGeometryType == GT_MESH)
{
CollisionPtr collision(new TreeCollision(
PhysicsManager::getSingleton()._getNewtonWorld(), entity, true));
mBody->setCollision(collision);
}
mBody->setPositionOrientation(position, orientation);
}
void PhysicalThing::freeze()
{
mBody->freeze();
}
void PhysicalThing::unfreeze()
{
mBody->unFreeze();
}
void PhysicalThing::setContactListener(PhysicsContactListener* listener)
{
mContactListener = listener;
}
PhysicsContactListener* PhysicalThing::getContactListener() const
{
return mContactListener;
}
void PhysicalThing::fitToPose(const Ogre::String& animName)
{
CollisionPtr coll;
if (mPhysicalObject->isMeshObject())
{
MeshObject* meshObject = dynamic_cast<MeshObject*>(mPhysicalObject);
//AxisAlignedBox size = meshObject->getPoseSize(name);
// Do we already have a collision for the wanted pose?
CollisionMap::iterator it = mPoseCollisions.find(animName);
if (it == mPoseCollisions.end())
{
Entity* entity = meshObject->getEntity();
MeshObject *tempMesh = NULL;
// the problem fixed and it's source:
// entity is a MeshObject containing the basic state of the Mesh, but
// this function should create the physical bounding convex hull for one of the
// animated states. Therefore the convex hull must be created from a mesh
// representing the animated state and not from a mesh containing the basic state
// check if this is a 'animated' state we have to create the convex hull for ...
if (animName != "" && meshObject->hasAnimation(animName)) {
// Duplicating the MeshObject and animate it into the animName pose
tempMesh = meshObject->createPosedCopy(animName);
entity = tempMesh->getEntity();
}
// create the collision primitive of the animated mesh
coll = PhysicsManager::getSingleton().createCollision(entity, mGeometryType, animName);
// cleanup the temporary mesh
delete tempMesh;
// No, so create it and put it into the map
mPoseCollisions.insert(make_pair(animName, coll));
}
else
{
// collision primitiv is cached, retrieve it
coll = it->second;
}
mBody->setCollision(coll);
// Set body-position so, that node-position is invariant.
setPosition(mActor->_getSceneNode()->_getDerivedPosition());
setOrientation(mActor->_getSceneNode()->_getDerivedOrientation());
}
else
{
Throw(IllegalArgumentException, "Poses are only supported by MeshObjects.");
}
}
void PhysicalThing::destroyPhysicsProxy()
{
delete mBody;
mBody = NULL;
}
void PhysicalThing::createPhysicsProxy(SceneNode* node)
{
if (!mBody)
{
Vector3 inertia;
OgreNewt::CollisionPtr coll = createCollision(mPhysicalObject, inertia);
OgreNewt::Body* body = new OgreNewt::Body(
PhysicsManager::getSingleton()._getNewtonWorld(), coll);
body->setMaterialGroupID(PhysicsManager::getSingleton().getMaterialID("default"));
Ogre::Real mass = mMass;
if (mass > 0.0 && mGeometryType != GT_MESH)
{
body->setMassMatrix(mass, inertia);
}
body->setCustomForceAndTorqueCallback(PhysicsManager::genericForceCallback);
setBody(body);
}
}
OgreNewt::CollisionPtr PhysicalThing::createCollision(PhysicalObject* po, Vector3& inertia) const
{
OgreNewt::CollisionPtr coll;
// there is a difference between a meshobject and a 'normal' object
// because a meshobject has got a mesh entity and therefore a it is
// likely that there will be more than one object with those collision
// primitives, so they need to get cached.
if (mPhysicalObject->isMeshObject())
{
Entity* entity = static_cast<MeshObject*>(mPhysicalObject)->getEntity();
coll = PhysicsManager::getSingleton().createCollision(
entity,
mGeometryType,
"",
NULL,
NULL,
mMass,
&inertia);
}
else
{
const AxisAlignedBox& aabb = mPhysicalObject->getDefaultSize();
coll = PhysicsManager::getSingleton().getCollisionFactory()->createCollisionFromAABB(
aabb,
mGeometryType,
NULL,
NULL,
mMass,
&inertia);
}
return coll;
}
void PhysicalThing::updatePhysicsProxy()
{
if (mBody)
{
mPoseCollisions.clear();
Vector3 inertia;
// update the collision
mBody->setCollision(createCollision(mPhysicalObject, inertia));
if (mMass > 0.0 && mGeometryType != GT_MESH)
{
mBody->setMassMatrix(mMass, inertia);
}
}
}
PhysicsController* PhysicalThing::getPhysicsController() const
{
return mPhysicsController;
}
void PhysicalThing::setPhysicsController(PhysicsController* controller)
{
if (mPhysicsController)
{
// if there is an old controller, remove it
mBody->setCustomForceAndTorqueCallback( PhysicsManager::genericForceCallback );
setUpConstraint(Vector3::ZERO);
mPhysicsController = NULL;
}
if(controller)
{
// prepare for control
mPhysicsController = controller;
//mBody->setAutoFreeze(0);
mBody->unFreeze();
mBody->setLinearDamping(0.0f);
mBody->setAngularDamping(Vector3::ZERO);
mBody->setCustomForceAndTorqueCallback( PhysicsManager::controlledForceCallback );
// Set up-vector, so force application doesn't let the char fall over
setUpConstraint(Vector3::UNIT_Y);
}
}
void PhysicalThing::setMaterialID(const OgreNewt::MaterialID* materialid)
{
mBody->setMaterialGroupID(materialid);
}
const OgreNewt::MaterialID* PhysicalThing::getMaterialID() const
{
return mBody->getMaterialGroupID();
}
}
| [
"melven@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
509
]
]
] |
bd80c1138acb2bce273c224be3b0d48515005cd6 | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /tool/dressing/source/bindobject/modelfile.cpp | 6f056225e845c25358a7c3af8ad0b458a9dc2661 | [] | no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | cpp | #include"stdafx.h"
#include"modelfile.h"
#include"../app.h"
using namespace Maid;
using namespace Sqrat;
void ModelFile::Register()
{
RootTable().Bind(
_SC("ModelFile"),
DerivedClassEx<ModelFile,CppDrawType,ModelFileAllocator>()
.SqObject(_SC("Matrix" ), &ModelFile::Matrix)
.Var(_SC("Alpha" ), &ModelFile::Alpha)
.Prop(_SC("FileName"), &ModelFile::GetFileName, &ModelFile::SetFileName)
);
}
ModelFile::ModelFile()
:Alpha(1)
{
HSQUIRRELVM v = DefaultVM::Get();
MAID_ASSERT( v==NULL, "VMが設定されていません" );
sq_resetobject( &Matrix );
}
ModelFile::~ModelFile()
{
HSQUIRRELVM v = DefaultVM::Get();
MAID_ASSERT( v==NULL, "VMが設定されていません" );
const SQBool drawtype = sq_release( v, &Matrix );
}
Sqrat::string ModelFile::GetFileName() const
{
const String str = Model.GetFileName();
const Sqrat::string ret = String::ConvertMAIDtoUNICODE(str);
return ret;
}
void ModelFile::SetFileName(const Sqrat::string& name)
{
const String str = String::ConvertUNICODEtoMAID(name);
const String dir = GetApp().GetCurrentDirectry();
Model.Load( dir + MAIDTEXT("\\") + str );
}
static const MATRIX4DF idx( MATRIX4DF().SetIdentity() );
void ModelFile::Draw( float time, const Maid::POINT3DF& pos )
{
if( Model.IsEmpty() ) { return ; }
if( Model.IsLoading() ) { return ; }
const CppMatrix* p = (const CppMatrix*)sq_objtoinstance(&Matrix);
const MATRIX4DF& mat = p==NULL? idx : p->GetMatrix();
const MATRIX4DF t = mat * MATRIX4DF().SetTranslate( pos.x, pos.y, pos.z );
GetApp().Get3DRender().Blt( t, Model, Alpha );
}
| [
"[email protected]"
] | [
[
[
1,
67
]
]
] |
b34f2659c0a6d0632992b66b06aa9141b852e24a | f77b2bf99f484dcfbb1840caa7c3a59a985fb44c | /MortController.h | 2038f1741eb012652e247aa6c487c420f98c08ad | [] | no_license | RaimonZamora/arounders | 1db9fc08a90a11f9a4555590cd30b073903dedf8 | 36d39effa4366afdf9f39a24229ac6b31ff70caa | refs/heads/master | 2020-12-24T15:49:09.758919 | 2009-12-10T09:07:19 | 2009-12-10T09:07:19 | 32,810,750 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | h | #pragma once
#include "SDL/SDL.h"
#include "DrawManager.h"
#include "InputManager.h"
#include "MusicManager.h"
#include "GameInfo.h"
class MortController
{
public:
MortController(DrawManager *p_drawManager, InputManager *p_inputManager, MusicManager *p_musicManager);
~MortController(void);
bool Init();
void Go(GameInfo *gameInfo);
void Finalize(void);
private:
DrawManager *drawManager;
InputManager *inputManager;
MusicManager *musicManager;
SDL_Surface *fondo;
SDL_Surface *cursor;
};
| [
"jaildoctor@051515c8-07d0-11de-9036-69e38a880166"
] | [
[
[
1,
25
]
]
] |
5f979bbee22db1d8f29976a26cc4bb5442639d77 | 29c00095e9aa05f7100561e490c65f71150fa93b | /config.hpp | 31348956c253e1f34c8e1817c69c51f55907dd13 | [
"Apache-2.0"
] | permissive | krfkeith/toupl | 1c78fe90a6516946a7f504d6c77ec746807e7ec8 | c80b5206750dc2de222e79c860cb229fb150a1fb | refs/heads/master | 2020-12-24T17:36:26.259097 | 2009-06-13T14:53:44 | 2009-06-13T14:53:44 | 37,639,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,193 | hpp | /*
This file is part of Toupl.
http://code.google.com/p/toupl/
Autor: Bga
Email: [email protected]
X.509 & GnuPG Email certifaces here: http://code.google.com/p/jbasis/downloads/list
Copyright 2009 Bga <[email protected]>
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
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 CONFIG_HPP
#define CONFIG_HPP
#define STRING_PROFILE_ENABLE 1
#define STRING_STD_SUPPORT_ENABLE 0
#define ASSERT_ENABLE 1
#define DEBUG_ENABLE 0
#endif
| [
"bga.email@31f10f56-5826-11de-b31f-81d54249e7d9"
] | [
[
[
1,
38
]
]
] |
7a98990bce16a4e2f3ba9e8d679228686a0a5c6f | e52b0e0e87fbeb76edd0f11a7e1b03d25027932e | /include/lua/LuaStackTableIterator.h | 692bf31e271ac4cca580d1f625e5089759a189c4 | [] | no_license | zerotri/Maxwell_Game_old | d9aaa4c38ee1b99fe9ddb6f777737229dc6eebeb | da7a02ff25697777efe285973e5cecba14154b6c | refs/heads/master | 2021-01-25T05:22:45.278629 | 2008-02-07T03:11:01 | 2008-02-07T03:11:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,946 | h | ///////////////////////////////////////////////////////////////////////////////
// This source file is part of the LuaPlus source distribution and is Copyright
// 2001-2004 by Joshua C. Jensen ([email protected]).
//
// The latest version may be obtained from http://wwhiz.com/LuaPlus/.
//
// The code presented in this file may be used in any environment it is
// acceptable to use Lua.
///////////////////////////////////////////////////////////////////////////////
#ifndef LUASTACKTABLEITERATOR_H
#define LUASTACKTABLEITERATOR_H
#ifdef _MSC_VER
#pragma once
#endif // _MSC_VER
///////////////////////////////////////////////////////////////////////////////
// namespace LuaPlus
///////////////////////////////////////////////////////////////////////////////
namespace LuaPlus
{
/**
The LuaStackTableIterator class provides a far simpler, safer, and more natural
looking table iteration method. The iterator is not STL compliant,
although it could easily be made so.
**/
class LUAPLUS_CLASS LuaStackTableIterator
{
public:
LuaStackTableIterator( LuaStackObject tableObj, bool doReset = true,
bool autoStackManagement = true );
~LuaStackTableIterator();
void Reset();
void Invalidate();
bool Next();
bool IsValid() const;
LuaStackTableIterator& operator++();
operator bool() const;
LuaStackObject GetKey();
LuaStackObject GetValue();
protected:
private:
/**
Don't allow copies. The stack will get screwed.
**/
LuaStackTableIterator& operator=( const LuaStackTableIterator& iter );
LuaStackTableIterator( const LuaStackTableIterator& iter );
LuaStackObject m_tableObj; ///< The table object being iterated.
int m_startStackIndex; ///< The current starting stack index or -1 if the iterator is invalid.
bool m_autoStackManagement; ///< Auto stack management enabled or not?
};
} // namespace LuaPlus
#endif // LUASTACKTABLEITERATOR_H
| [
"[email protected]"
] | [
[
[
1,
60
]
]
] |
eff17420e8252da7c23e74a03731ef903b0db3cd | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/net/impl/wscDatagramSocketImplFactory.h | 6b5899098a345586074de1569565e09201aca529 | [] | no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 639 | h | #pragma once
#include <wcpp/net/wsiDatagramSocketImplFactory.h>
#include <wcpp/lang/wscObject.h>
#define WS_ClassName_OF_wscDatagramSocketImplFactory "wcpp.net.impl.wscDatagramSocketImplFactory"
class wscDatagramSocketImplFactory : public wscObject , public wsiDatagramSocketImplFactory
{
WS_IMPL_QUERY_INTERFACE_BEGIN( wscDatagramSocketImplFactory )
WS_IMPL_QUERY_INTERFACE_BODY( wsiDatagramSocketImplFactory )
WS_IMPL_QUERY_INTERFACE_END()
public:
static const ws_char * const s_class_name;
public:
wscDatagramSocketImplFactory(void);
~wscDatagramSocketImplFactory(void);
};
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
] | [
[
[
1,
21
]
]
] |
7dea90a05af0bca6c4ba7e6012bba93a08659255 | 4758b780dad736c20ec46e3e901ecdf5a0921c04 | /vm/int/SourceCode/IGD480.cpp | f1308cfb96e52ffe378c56219f31a9ce6be2293b | [] | no_license | arbv/kronos | 8f165515e77851d98b0e60b04d4b64d5bc40f3ea | 4974f865161b78161011cb92223bef45930261d9 | refs/heads/master | 2023-08-19T18:56:36.980449 | 2008-08-23T19:44:08 | 2008-08-23T19:44:08 | 97,011,574 | 1 | 1 | null | 2017-07-12T13:31:54 | 2017-07-12T13:31:54 | null | UTF-8 | C++ | false | false | 14,762 | cpp | ///////////////////////////////////////////////////////////////////
// IGD480.cpp
#include "preCompiled.h"
#include "resource.h"
#include "MEMORY.h"
#include "IGD480.h"
IGD480::IGD480(MEMORY* m, SioMouse* sioMouse, Console* con) :
thread(null),
bRun(true),
hWnd(null),
hBitmap(null),
hbmpScreen(null),
pBits(null),
lResult(0),
hStaticWnd(null),
mdc(null),
bdc(null),
dwShift(0),
dwLock(0xFFFFFFFF),
nCursor(0),
mem(*m),
mx(480/2),
my(360/2),
mouse(*sioMouse),
console(*con)
{
dword id = 0;
thread = ::CreateThread(null, 0, rawDisplayThread, (void*)this, 0, &id);
::SetThreadPriority(thread, THREAD_PRIORITY_BELOW_NORMAL);
// THREAD_PRIORITY_LOWEST?
// THREAD_PRIORITY_IDLE
}
IGD480::~IGD480()
{
shutdown();
if (hBitmap != null)
{
::DeleteObject(hBitmap); hBitmap = null;
::DeleteObject(hbmpScreen); hbmpScreen = null;
::DeleteDC(mdc); mdc = null;
::DeleteDC(bdc); bdc = null;
}
pBits = null;
}
dword IGD480::displayThread()
{
while (bRun)
{
::Sleep(20); // ~50 frames per second
dword shift = mem.data[IGD480base + 0x00] & ~0x1;
dword lock = mem.data[IGD480base + 0x0F];
if (lock != dwLock)
{
// trace("lock=%d\n", lock);
dwLock = lock;
if (hWnd == null)
{
createWindow();
createBitmap();
}
if (hWnd != null)
{
::ShowWindow(hWnd, dwLock ? SW_SHOW : SW_HIDE);
if (dwLock)
{
::SetForegroundWindow(hWnd);
::BringWindowToTop(hWnd);
::SetWindowPos(hWnd, HWND_TOP, -1, -1, -1, -1, SWP_NOMOVE|SWP_NOSIZE);
}
if (dwLock) // all Kronos programs start with cursor in the middle
{
mx = 480 / 2;
my = 360 / 2;
}
}
}
mem.data[IGD480base + 0x00] |= 0x01; // frame sync
if (shift != dwShift)
{
dwShift = shift;
trace("dwShift=%08X\n", dwShift);
}
// mem.data[IGD480base + 0x20] &= ~0x01; // line sync (not necessary, faster w/o it)
refresh();
::Sleep(100);
mem.data[IGD480base + 0x00] &= ~0x01; // frame sync
// mem.data[IGD480base + 0x20] |= 0x01; // line sync (not necessary, faster w/o it)
}
return 0;
}
void IGD480::shutdown()
{
bRun = false;
if (thread != null)
{
::WaitForSingleObject(thread, 1000);
::CloseHandle(thread); thread = null;
}
if (hWnd != null)
{
::DestroyWindow(hWnd); hWnd = null;
::Sleep(200);
}
}
dword IGD480::rawDisplayThread(void* pvThis)
{
IGD480* pThis = (IGD480*)pvThis;
return pThis->displayThread();
}
/////////////////////////////////////////////////////////////////
void IGD480::onPaint()
{
}
//CONST trans = ARRAY OF BITSET{{},{2},{1},{1..2},{0},{0,2},{0..1},{0..2}};
int trans[8] = { 0x0, 0x4, 0x2, 0x6, 0x1, 0x5, 0x3, 0x7 };
// assert(trans[trans[i]] == i);
bool IGD480::wndProc(UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_KEYDOWN:
// trace("WM_KEYDOWN=%02x\n", wParam & 0xFF);
if (VK_PRIOR <= wParam && wParam <= VK_HELP
|| VK_F1 <= wParam && wParam <= VK_F12)
{
// we won't receive WM_CHAR on those
console.onKey(true, wParam, 0x00000001, wParam & 0xFF);
}
break;
case WM_KEYUP:
console.onKey(false, wParam, lParam, wParam & 0xFF);
// trace("WM_KEYUP=%02x\n", wParam & 0xFF);
break;
case WM_CHAR:
console.onKey(true, wParam, lParam, wParam & 0xFF);
// trace("WM_CHAR=%02x\n", wParam & 0xFF);
return true;
case WM_SYSCOMMAND:
{
dword uCommand = wParam & ~0xF;
if (uCommand == SC_MOVE
|| uCommand == SC_MINIMIZE
|| uCommand == SC_RESTORE)
break; // continue processing
else
return true; // prohib others
}
case WM_ERASEBKGND:
return true;
case WM_GETICON:
lResult = (LRESULT)::LoadIcon(::GetModuleHandle(null),
MAKEINTRESOURCE(IDI_KRONOS));
return true;
case WM_NCMOUSEMOVE:
if (nCursor > 0)
{
::ShowCursor(true);
nCursor--;
}
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MOUSEMOVE:
{
dword dwKeys = wParam; // key flags
int xPos = LOWORD(lParam); // horizontal position of cursor
int yPos = HIWORD(lParam); // vertical position of cursor
RECT rc;
::GetClientRect(hWnd, &rc);
POINT pt;
pt.x = xPos;
pt.y = yPos;
// trace("%d %d\n", xPos, yPos);
if (::PtInRect(&rc, pt))
{
if (nCursor == 0)
{
::ShowCursor(false);
nCursor++;
}
}
else
{
}
dword dwState = 0;
dwState |= (dwKeys & MK_LBUTTON) ? 0x1 : 0x0;
dwState |= (dwKeys & MK_RBUTTON) ? 0x2 : 0x0;
dwState |= (dwKeys & MK_MBUTTON) ? 0x4 : 0x0;
dwState ^= 0x7;
yPos = rc.bottom - yPos - 1;
// trace("%d %d was %d %d\n", xPos, yPos, mx, my);
mouse.changeState(trans[dwState], xPos - mx, yPos - my);
mx = xPos;
my = yPos;
return true;
}
}
return false;
}
LRESULT IGD480::rawWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
bool bProcessed = false;
IGD480* pThis = null;
if (msg == WM_CREATE)
{
CREATESTRUCT* pCS = (CREATESTRUCT*)lParam;
pThis = (IGD480*)pCS->lpCreateParams;
::SetWindowLong(hWnd, GWL_USERDATA, (long)pCS->lpCreateParams);
pThis->lResult = 0;
pThis->hWnd = hWnd;
bProcessed = pThis->wndProc(msg, wParam, lParam);
}
else
{
pThis = (IGD480*)GetWindowLong(hWnd, GWL_USERDATA);
if (pThis != null)
{
pThis->lResult = 0;
bProcessed = pThis->wndProc(msg, wParam, lParam);
}
}
if (!bProcessed)
return ::DefWindowProc(hWnd, msg, wParam, lParam);
else
return pThis->lResult;
}
void IGD480::createWindow()
{
WNDCLASS cls;
cls.style = CS_VREDRAW|CS_HREDRAW;
cls.style &= ~CS_DBLCLKS;
cls.lpfnWndProc = rawWndProc;
cls.cbClsExtra = 0;
cls.cbWndExtra = 0;
cls.hInstance = ::GetModuleHandle(null);
cls.hIcon = ::LoadIcon(cls.hInstance, MAKEINTRESOURCE(IDI_KRONOS));
cls.hCursor = ::LoadCursor(null, IDC_CROSS);
cls.hbrBackground = (HBRUSH)::GetStockObject(NULL_BRUSH);
cls.lpszMenuName = null;
cls.lpszClassName = "KronosIGD480";
dword dwStyle = WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX;
RECT rc = {0, 0, 480, 360};
AdjustWindowRectEx(&rc, dwStyle, /*menu:*/false, WS_EX_APPWINDOW);
hWnd = ::CreateWindowEx(WS_EX_APPWINDOW,
(const char*)::RegisterClass(&cls),
"Kronos Graphics",
dwStyle,
CW_USEDEFAULT, CW_USEDEFAULT,
rc.right - rc.left, rc.bottom - rc.top,
null, null,
::GetModuleHandle(null),
this);
HMENU hMenu = ::GetSystemMenu(hWnd, false);
::DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
::DeleteMenu(hMenu, SC_MAXIMIZE, MF_BYCOMMAND);
::DeleteMenu(hMenu, SC_SIZE, MF_BYCOMMAND);
::DeleteMenu(hMenu, GetMenuItemCount(hMenu)-1, MF_BYPOSITION);
hStaticWnd = ::CreateWindow("STATIC", null, WS_CHILD|WS_VISIBLE|SS_BITMAP,
0, 0, 480, 360, hWnd, null,
GetModuleHandle(null), null);
mdc = ::CreateCompatibleDC(null);
bdc = ::CreateCompatibleDC(null);
}
void IGD480::createBitmap()
{
BITMAPINFO bmi;
memset(&bmi, 0, sizeof bmi);
BITMAPINFOHEADER& bih = bmi.bmiHeader;
bih.biSize = sizeof bmi;
bih.biWidth = 480;
bih.biHeight = 360;
bih.biPlanes = 1;
bih.biBitCount = 24;
bih.biCompression = 0;
bih.biSizeImage = (bih.biWidth * bih.biHeight * bih.biBitCount * bih.biPlanes) / 8;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
::GdiFlush();
hBitmap = ::CreateDIBSection(mdc, (const BITMAPINFO*)&bmi, 0, (void**)&pBits, NULL, 0);
HDC hDC = ::GetDC(hStaticWnd);
hbmpScreen = ::CreateCompatibleBitmap(hDC, 480, 360);
::ReleaseDC(hStaticWnd, hDC);
::SendMessage(hStaticWnd, STM_SETIMAGE, IMAGE_BITMAP, long(hbmpScreen));
}
const int ptrans[] =
{ 0xF,0x7,0xB,0x3,0xD,0x5,0x9,0x1,0xE,0x6,0xA,0x2,0xC,0x4,0x8,0x0 };
void IGD480::copyBitmap()
{
// dwShift:
// shy0 = 151+512; -- 151 + 360 == 511
// sh := ((shy0-screen.ldcy)*200h+screen.ldcx)*400h;
int ldcy = ((dwShift / 0x400) / 0x200) % 512;
int ldcx = ((dwShift / 0x400) % 0x200) % 512;
dword* pal = (dword*)(byte*)&mem[IGD480base + 0x10];
byte palette[16][3];
for (int i = 0; i < 16; i++)
{
assert(ptrans[ptrans[i]] == i);
int c = pal[i];
c = pal[i]; int r = ptrans[c % 16] / 4;
c = c / 16; int g = ptrans[c % 16] / 4;
c = c / 16; int b = ptrans[c % 16] / 4;
r = (r == 0 ? 0 : (r+1) * 64 - 1);
g = (g == 0 ? 0 : (g+1) * 64 - 1);
b = (b == 0 ? 0 : (b+1) * 64 - 1);
palette[i][0] = (byte)r;
palette[i][1] = (byte)g;
palette[i][2] = (byte)b;
}
const int wpl = 512 / 32;
for (int y = 0; y < 360; y++)
{
int x = 0; // should also be refrelecting ldcx
for (int i = 0; i < 480 / 32; i++)
{
int Y = (ldcy + y) % 512;
dword w0 = mem[IGD480bitmap + (Y + 0*512) * wpl + ldcx / 32 + i];
dword w1 = mem[IGD480bitmap + (Y + 1*512) * wpl + ldcx / 32 + i];
dword w2 = mem[IGD480bitmap + (Y + 2*512) * wpl + ldcx / 32 + i];
dword w3 = mem[IGD480bitmap + (Y + 3*512) * wpl + ldcx / 32 + i];
for (int j = 0; j < 32; j++)
{
int n =
((w0 << 0) & 0x1) |
((w1 << 1) & 0x2) |
((w2 << 2) & 0x4) |
((w3 << 3) & 0x8);
pBits[((359-y)*480 + x) * 3 + 0] = palette[n][2]; // B
pBits[((359-y)*480 + x) * 3 + 1] = palette[n][1]; // G
pBits[((359-y)*480 + x) * 3 + 2] = palette[n][0]; // R
x++;
assert(x <= 480);
w0 >>= 1;
w1 >>= 1;
w2 >>= 1;
w3 >>= 1;
}
}
}
}
void IGD480::refresh()
{
MSG msg;
while (::PeekMessage(&msg, 0, 0, null, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
if (!::IsIconic(hWnd) && ::IsWindowVisible(hWnd))
{
//::GdiFlush(); ??
// trace("BitBlt\n");
copyBitmap();
HGDIOBJ hMdcSafeBmp = ::SelectObject(mdc, hBitmap);
HGDIOBJ hBdcSafeBmp = ::SelectObject(bdc, hbmpScreen);
int nOldStretchMode = ::SetStretchBltMode(bdc, HALFTONE);
POINT pt = {0,0};
BOOL bSetOrigin = ::SetBrushOrgEx(bdc, 0, 0, &pt);
(void)bSetOrigin; // unused
BOOL r = ::BitBlt(bdc, 0, 0, 480, 360, mdc, 0, 0, SRCCOPY);
(void)r; // unused
::SetStretchBltMode(bdc, nOldStretchMode);
::SelectObject(bdc, hBdcSafeBmp);
::SelectObject(mdc, hMdcSafeBmp);
::InvalidateRect(hStaticWnd, null, false);
::InvalidateRect(hWnd, null, false);
}
}
#pragma warning(disable: 4355) // 'this' : used in base member initializer list
SioMouse::SioMouse(int addr, int ipt) :
i(new cI(addr, ipt, this)), nIn(0), nOut(0)
{
memset(buf, 0, sizeof buf);
}
#pragma warning(default: 4355) // 'this' : used in base member initializer list
SioMouse::~SioMouse()
{
delete i;
}
int SioMouse::addr()
{
return i->addr();
}
int SioMouse::ipt()
{
return i->ipt();
}
int SioMouse::inpIpt()
{
return i->inpIpt();
}
int SioMouse::outIpt()
{
return i->outIpt();
}
int SioMouse::inp(int addr)
{
return i->inp(addr);
}
void SioMouse::out(int addr, int data)
{
i->out(addr, data);
}
int SioMouse::busyRead()
{
int in = nIn;
int out = nOut;
if (in == out)
return EMPTY;
else
{
char ch = buf[out];
out = (out+1) % (sizeof buf);
::InterlockedExchange(&nOut, out);
// trace("SioMouse::busyRead()(%02X)\n", ch);
return ch;
}
}
void SioMouse::write(char*, int)
{
// nothing
}
void SioMouse::writeChar(char)
{
// nothing
}
void SioMouse::changeState(dword dwKeys, int dx, int dy)
{
// trace("mouse.changeState(%d %d)\n", dx, dy);
if (dx < -512)
dx = -512;
if (dy < -512)
dy = -512;
if (dx > 511)
dx = 511;
if (dy > 511)
dy = 511;
// trace("SioMouse::changeState(%0X, %d, %d)\n", dwKeys, dx, dy);
int j = nIn;
long nNewIn = (nIn + 5) % (sizeof buf);
buf[j++] = byte((dwKeys & 0x7) + 0200);
buf[j++] = byte(dx & 0xFF); dx >>= 8;
buf[j++] = byte(dy & 0xFF); dy >>= 8;
buf[j++] = byte(dx & 0xFF);
buf[j++] = byte(dy & 0xFF);
assert(j <= sizeof buf);
::InterlockedExchange(&nIn, nNewIn);
}
//
/////////////////////////////////////////////////////////////////
| [
"leo.kuznetsov@4e16752f-1752-0410-94d0-8bc3fbd73b2e"
] | [
[
[
1,
529
]
]
] |
7dfce8bc4eb4c02243415eb983da4e50f7541ce1 | c02cb25416f1f32b1264792c256bc8e9ddb36463 | /CFractalIntro.h | c63947ae2b0eac90b3f5b6cbdf1c3e95a9994a40 | [] | no_license | tronster/node | 230b60095202c9e8c7459c570d1d6b1689730786 | ea14fc32bbbadf24549f693b3cd52b7423fc4365 | refs/heads/master | 2016-09-05T22:32:32.820092 | 2011-07-12T23:29:48 | 2011-07-12T23:29:48 | 2,039,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,945 | h | #ifndef __CFractalIntro_h__
#define __CFractalIntro_h__
#pragma warning(disable:4786)
#ifdef _DEBUG
#include "gldebug.h"
#endif
#include "CDemoEffect.h"
#include "geometry3d.h"
#include "flythru3d.h"
#include "mduke.h"
#include "tiler.h"
#include "CIFS.h"
class CFractalIntro : public CDemoEffect
{
public:
// CDemoEffect
CFractalIntro(CEnvInfo *);
~CFractalIntro();
// vidGL virtual overrides
bool renderFrame();
bool advanceFrame();
bool init();
bool unInit();
bool start();
bool stop();
protected:
// Lights, Camera
geoGL::Light3D light0; // Standard light
geoGL::Camera3D cam;
// Action
refptr<geoGL::ObjectSet3D> objCube;
CTilerGL tileBG;
md::Cimage oBigBackground;
int nCenterTile;
// Fractal tree
CIFS tree1;
refptr<geoGL::fVector2D> pPointsGrow;
float fCurrDepth;
// Wind on tree
float fWindX, fWindY;
// Symbols
refptr<geoGL::TextureID> pSymbols;
geoGL::ObjectSet3D objSymbol;
int nSymbol;
float fSymFactor;
// Timing, CDemoEffect
CEnvInfo & m_oEnvInfo;
unsigned int nTimeStart, nElapsedTime;
float fLineScale;
// CFractalIntro
void loadGLTextures();
void initGLstuff();
void initObjects();
void initTree();
bool renderSymbols();
bool renderTree();
bool renderBackground();
bool renderParticles();
bool advanceSymbols();
bool advanceTree();
bool advanceBackground();
bool advanceParticles();
GLuint loadGLTexture(md::CmediaDuke &, char *filename, char *textureName=NULL);
};
#endif | [
"[email protected]"
] | [
[
[
1,
78
]
]
] |
7948b8ba0fccf023d7b26e7a7875a5b50fed553b | ad00c3a132f75a71bf763ce0aa70742fcede5ce8 | /DotnetServer/PacketBuilder.h | 19153434beeb0db6cd4841b3e8d2fc69f2c1eb87 | [] | no_license | Dracar/samp-dotnet-script-api | 6975208c1beab28bed2480602c232f737f0bd86b | d88ddfcb9c52a807d3eb8e74607c0857f184d006 | refs/heads/master | 2021-01-22T03:57:49.952418 | 2011-12-22T15:40:12 | 2011-12-22T15:40:12 | 42,196,278 | 0 | 0 | null | null | null | null | WINDOWS-1258 | C++ | false | false | 2,874 | h | /*
* Iain Gilbert
* 2011
*
*/
/*
The contents of this file are subject to the Common Public Attribution License Version 1.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.opensource.org/licenses/cpal_1.0
The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 have been added to cover use of software over a computer network and provide for limited attribution for the Original Developer.
In addition, Exhibit A has been modified to be consistent with Exhibit B.
Software distributed under the License is distributed on an “AS IS” basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations under the License.
The Original Code is SampDotnetScriptAPI.
The Initial Developer of the Original Code is Iain Gilbert. All portions of the code written by Iain Gilbert are Copyright (c) 2011. All Rights Reserved.
Contributors: ______________________.
The text of this license may differ slightly from the text of the notices in Exhibits A and B of the license at http://code.google.com/p/samp-dotnet-script-api/.
You should use the latest text at http://code.google.com/p/samp-dotnet-script-api/ for your modifications.
You may not remove this license text from the source files.
Attribution Information
Attribution Copyright Notice:
Attribution Phrase (not exceeding 10 words): Samp Dotnet Script API
Attribution URL: http://code.google.com/p/samp-dotnet-script-api/
Display of Attribution Information to the end user is not required on server login, or at any time the end user is connected to your server.
You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2.
Display of Attribution Information is not required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
*/
#pragma once
#include "main.h"
#include "Log.h"
#include "Client.h"
#include "NativeFunctionProcessor.h"
//class Server;
class PacketBuilder
{
public:
PacketBuilder();
void SendPingRequest(Client* client);
void SendAuthReply(Client* client,bool success);
void SendFunctionResponse(Client* client,FunctionRequest* function);
/*void SendCallbackToAll(Packet* sp);
void SendCallback(Client* client, Packet* sp);
void SendFunctionRequestToAll(Packet* sp);
void SendFunctionRequest(Client* client, Packet* sp);*/
void SendPacketToAll(Packet* sp);
void SendTest(Client* client);
private:
};
| [
"[email protected]"
] | [
[
[
1,
62
]
]
] |
61de73ca5a24f103bd006a5815cbb4a74e740e48 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/MD5/MD5Builder/MD5BuilderDlg.cpp | d57a10012034f79d76d71aaad181c718253e0a3a | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,299 | cpp | // MD5BuilderDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "MD5Builder.h"
#include "MD5BuilderDlg.h"
#include ".\md5builderdlg.h"
#include "tools.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMD5BuilderDlg 对话框
CMD5BuilderDlg::CMD5BuilderDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMD5BuilderDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMD5BuilderDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMD5BuilderDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDOK, OnBnClickedOk)
END_MESSAGE_MAP()
// CMD5BuilderDlg 消息处理程序
BOOL CMD5BuilderDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
return TRUE; // 除非设置了控件的焦点,否则返回 TRUE
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CMD5BuilderDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标显示。
HCURSOR CMD5BuilderDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CMD5BuilderDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
//OnOK();
CString str;
this->GetDlgItemText(IDC_EDIT2,str);
char strResult[256]={0,} ;
md5( strResult, str );
this->SetDlgItemText(IDC_EDIT1,strResult);
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
98
]
]
] |
eaaf069ab716518e02f50e6fc2377b44efaf5781 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/engine/rb_core/jref.h | d0fe38de8134ec793329b2d4cb6e952882443f5b | [] | no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 1,051 | h | //****************************************************************************/
// File: JRef.h
//****************************************************************************/
#ifndef __JREF_H__
#define __JREF_H__
//****************************************************************************/
// Class: JRef
// Desc: Used as reference to some another object
//****************************************************************************/
class JRef : public JObject
{
JString m_Object;
JWeakRef<JObject> m_pObject;
public:
JRef () : m_pObject( NULL ) {}
virtual void Render ();
virtual void Init ();
const char* GetObject () const { return m_Object.c_str(); }
void SetObject ( const char* name );
expose(JRef)
{
parent(JObject);
prop( "Object", GetObject, SetObject );
}
}; // class JRef
#endif // __JREF_H__
| [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
0f1d22ad26142ebf11a2ae56a3e70303d5c96582 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /ToolsAndUtilities/Localise/HelloWorld_Main.cpp | 08b30b5486b3d9e461809a7c8bedc858aabd234d | [] | no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,614 | cpp | // HelloWorld_Main.cpp
// -------------------
//
// Copyright (c) 2000 Symbian Ltd. All rights reserved.
//
////////////////////////////////////////////////////////////////////////
//
// HelloWorld
// ----------
//
//
// The example is a simple application containing a single view with
// the text "Hello World !" drawn on it.
//
// The example includes code for displaying a very simple menu.
//
// ---------------------------------------------------------------------
//
// This source file contains the single exported function required by
// all UI applications and the E32Dll function which is also required
// but is not used here.
//
////////////////////////////////////////////////////////////////////////
#include "HelloWorld.h"
// The entry point for the application code. It creates
// an instance of the CApaApplication derived
// class, CExampleApplication.
//
#if defined(EKA2)
#include <eikstart.h>
LOCAL_C CApaApplication* NewApplication()
{
return new CExampleApplication;
}
GLDEF_C TInt E32Main()
{
return EikStart::RunApplication(NewApplication);
}
#endif
#if defined(__WINS__) && !defined(EKA2)
// This function is required by all Symbian OS DLLs. In this
// example, it does nothing.
EXPORT_C CApaApplication* NewApplication()
{
return new CExampleApplication;
}
GLDEF_C TInt E32Dll(TDllReason)
{
return KErrNone;
}
EXPORT_C TInt WinsMain(TDesC* aCmdLine)
{
return EikStart::RunApplication(NewApplication, aCmdLine);
}
#endif
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
68
]
]
] |
f9fad93b024f5e7233413c3df731c3545c892358 | a699a508742a0fd3c07901ab690cdeba2544a5d1 | /RailwayDetection/KellService/LogFileSystem/AfxLogFileSystem.h | f0452757ec136e1ec081822685a143668e5ad362 | [] | no_license | xiaomailong/railway-detection | 2bf92126bceaa9aebd193b570ca6cd5556faef5b | 62e998f5de86ee2b6282ea71b592bc55ee25fe14 | refs/heads/master | 2021-01-17T06:04:48.782266 | 2011-09-27T15:13:55 | 2011-09-27T15:13:55 | 42,157,845 | 0 | 1 | null | 2015-09-09T05:24:10 | 2015-09-09T05:24:09 | null | UTF-8 | C++ | false | false | 482 | h | // LogFileSystem.h : main header file for the LogFileSystem DLL
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CLogFileSystemApp
// See LogFileSystem.cpp for the implementation of this class
//
class CLogFileSystemApp : public CWinApp
{
public:
CLogFileSystemApp();
// Overrides
public:
virtual BOOL InitInstance();
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3"
] | [
[
[
1,
27
]
]
] |
49f8ca3e4c1a385f3ebb80d8158bf042faf781a9 | 57855d23617d6a65298c2ae3485ba611c51809eb | /Zen/EnterprisePlugins/Account/AccountService/src/AccountService.hpp | 32d8c11b0feb8e9a40a409f11ca8bcfc3b335270 | [] | no_license | Azaezel/quillus-daemos | 7ff4261320c29e0125843b7da39b7b53db685cd5 | 8ee6eac886d831eec3acfc02f03c3ecf78cc841f | refs/heads/master | 2021-01-01T20:35:04.863253 | 2011-04-08T13:46:40 | 2011-04-08T13:46:40 | 32,132,616 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,963 | hpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Enterprise Framework
//
// Copyright (C) 2001 - 2010 Tony Richards
// Copyright (C) 2008 - 2010 Matthew Alan Gray
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Tony Richards [email protected]
// Matthew Alan Gray [email protected]
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#ifndef ZEN_ENTERPRISE_ACCOUNT_SERVICE_ACCOUNT_SERVICE_HPP_INCLUDED
#define ZEN_ENTERPRISE_ACCOUNT_SERVICE_ACCOUNT_SERVICE_HPP_INCLUDED
#include "Account.hpp"
#include <Zen/EnterprisePlugins/Account/AccountServer/I_AccountService.hpp>
#include <Zen/Core/Event/I_EventManager.hpp>
#include <Zen/Core/Event/I_EventService.hpp>
#include <Zen/Enterprise/AppServer/scriptable_generic_service.hpp>
#include "../Model/I_AccountDataMap.hpp"
#include "../Model/I_AccountDomainObject.hpp"
#include "../Model/I_AccountDataCollection.hpp"
#include <boost/cstdint.hpp>
#include <set>
#include <map>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Enterprise {
namespace Account {
namespace Service {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class AccountService
: public Zen::Enterprise::AppServer::scriptable_generic_service
<Server::I_AccountService, AccountService>
{
/// @name Types
/// @{
public:
/// @}
/// @name I_StartupShutdownParticipant implementation
/// @{
public:
virtual void setConfiguration(const Zen::Plugins::I_ConfigurationElement& _config);
virtual Zen::Threading::I_Condition* prepareToStart(Zen::Threading::ThreadPool& _threadPool);
virtual void start();
virtual Zen::Threading::I_Condition* prepareToStop();
virtual void stop();
/// @}
/// @name I_ScriptableType implementation
/// @{
public:
virtual const std::string& getScriptTypeName();
virtual Scripting::I_ObjectReference* getScriptObject();
/// @}
/// @name I_ScriptableService implementation
/// @{
public:
virtual void registerScriptEngine(pScriptEngine_type _pScriptEngine);
/// @}
/// @name I_AccountService implemenation
/// @{
public:
virtual pFutureAccount_type createAccount(const std::string& _userId, const std::string& _password);
virtual void subscribe(Enterprise::Session::I_Session& _session, pEndpoint_type _pEndpoint, pResourceLocation_type _pLocation);
virtual pFutureAccount_type updateAccount(pAccount_type _pAccount);
virtual void deleteAccount(pAccount_type _pAccount);
virtual boost::uint64_t authenticate(pEndpoint_type _pDestinationEndpoint,
pResourceLocation_type _pDestLocation,
const std::string& _name,
const std::string& _password);
virtual Event::I_Event& getAuthenticationEvent();
/// @}
/// @name AccountService implemenation
/// @{
public:
pScriptModule_type getScriptModule();
void loadAccounts();
void handleAuthenticateRequest(pRequest_type _pRequest, pResponseHandler_type);
boost::uint64_t generateNativeAccountId();
/// @}
/// @name 'Structors
/// @{
protected:
friend class AccountServiceFactory;
AccountService(Zen::Enterprise::AppServer::I_ApplicationServer& _appServer);
virtual ~AccountService();
/// @}
/// @name Member Variables
/// @{
private:
pScriptEngine_type m_pScriptEngine;
Zen::Scripting::script_module* m_pScriptModule;
Scripting::I_ObjectReference* m_pScriptObject;
const Zen::Plugins::I_ConfigurationElement* m_pDatabaseConfig;
typedef Zen::Memory::managed_ptr<Zen::Enterprise::Account::Model::I_AccountDomainObject> pAccountObject_type;
typedef std::map<boost::uint64_t, pAccountObject_type> Accounts_type;
Accounts_type m_accountsMap;
typedef std::map<std::string, boost::uint64_t> UsersToAccountIds_type;
UsersToAccountIds_type m_usersToAccountIds;
boost::uint64_t m_lastAccountId;
Zen::Threading::I_Mutex* m_pAccountIdMutex;
Zen::Threading::I_Condition* m_pAccountsLoadedCondition;
/// TODO Use an AccountClient service here for authentication.
//typedef Zen::Memory::managed_ptr<Zen::Enterprise::Account::Client::I_AccountService> pClientAccountService_type;
//pClientAccountService_type m_pClientAccountService;
/// @}
};
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Service
} // namespace Account
} // namespace Enterprise
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#endif // ZEN_ENTERPRISE_ACCOUNT_SERVICE_ACCOUNT_SERVICE_HPP_INCLUDED
| [
"trichards@localhost"
] | [
[
[
1,
154
]
]
] |
40086a98a17ac8cb8ddf491e519a50e16c66baf3 | 042a5b8f07ce631d8ed1ac32a57248a423693fb4 | /Project/Physx.h | 36f12f0a1580439bdf03abc9d1c4e205219ef1ca | [] | no_license | gmasucci/physics-ballistics-demo | c4e576bc70a2264937960df77f5af90134eb503c | 8f8924b5a04a8d9a3cbde90cbf0a4dc5c8b224db | refs/heads/master | 2021-01-10T10:53:59.838036 | 2011-04-26T14:18:32 | 2011-04-26T14:18:32 | 36,923,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | h | #pragma once
#include "enumerations.h"
//const long double PI = 3.1415926535897932384626433832795028841968;
class Physx
{
public:
Physx(void);
~Physx(void);
// general functions
float toRads(float theta) { return theta*(PI/180); }
float acceleration(float force, float mass) { return force/mass; }
float updateYposByGravity(float oldPosition) { return oldPosition + (GRAVITY/FRAMERATE); }
float updatePosByWind() {/* need this later, updates all 3 axis coordinates*/}
inline float squared(float numToSqr) { return numToSqr * numToSqr; }
inline float cubed(float numToCube) { return numToCube * numToCube * numToCube; }
protected:
double mass;
double angle;
};
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
af64eb0659b9491ab75efa4a8999996238d22d23 | ce87282d8a4674b2c67bde4b7dbac165af73715b | /propgrid/patch_wx26/include/wx/variant.h | a5e7013b99cbf6d1b5dde100f23b0c800356f460 | [] | no_license | Bluehorn/wxPython | b07ffc08b99561d222940753ab5074c6a85ba962 | 7b04577e268c59f727d4aadea6ba8a78638e3c1b | refs/heads/master | 2021-01-24T04:20:21.023240 | 2007-08-15T21:01:30 | 2016-01-23T00:46:02 | 8,418,914 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,305 | h | /////////////////////////////////////////////////////////////////////////////
// Name: wx/variant.h
// Purpose: wxVariant class, container for any type
// Author: Julian Smart
// Modified by:
// Created: 10/09/98
// RCS-ID: $Id: variant.h,v 1.51 2006/11/03 21:37:08 VZ Exp $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_VARIANT_H_
#define _WX_VARIANT_H_
#include "wx/defs.h"
#include "wx/object.h"
#include "wx/string.h"
#include "wx/arrstr.h"
#include "wx/list.h"
#define wxUSE_VARIANT 1
#if wxUSE_DATETIME
#include "wx/datetime.h"
#endif // wxUSE_DATETIME
#if wxUSE_ODBC
#include "wx/db.h" // will #include sqltypes.h
#endif //ODBC
#include "wx/iosfwrap.h"
#define wxVARIANT_REFCOUNTED 1
/*
* wxVariantData stores the actual data in a wxVariant object,
* to allow it to store any type of data.
* Derive from this to provide custom data handling.
*
* NB: To prevent addition of extra vtbl pointer to wxVariantData,
* we don't multiple-inherit from wxObjectRefData. Instead,
* we simply replicate the wxObject ref-counting scheme.
*
* NB: When you construct a wxVariantData, it will have refcount
* of one. Refcount will not be further increased when
* it is passed to wxVariant. This simulates old common
* scenario where wxVariant took ownership of wxVariantData
* passed to it.
* If you create wxVariantData for other reasons than passing
* it to wxVariant, technically you are not required to call
* DecRef() before deleting it.
*
* TODO: in order to replace wxPropertyValue, we would need
* to consider adding constructors that take pointers to C++ variables,
* or removing that functionality from the wxProperty library.
* Essentially wxPropertyValue takes on some of the wxValidator functionality
* by storing pointers and not just actual values, allowing update of C++ data
* to be handled automatically. Perhaps there's another way of doing this without
* overloading wxVariant with unnecessary functionality.
*/
class WXDLLIMPEXP_BASE wxVariantData: public wxObject
{
friend class wxVariant;
public:
wxVariantData()
: wxObject(), m_count(1)
{ }
// Override these to provide common functionality
virtual bool Eq(wxVariantData& data) const = 0;
#if wxUSE_STD_IOSTREAM
virtual bool Write(wxSTD ostream& WXUNUSED(str)) const { return false; }
#endif
virtual bool Write(wxString& WXUNUSED(str)) const { return false; }
#if wxUSE_STD_IOSTREAM
virtual bool Read(wxSTD istream& WXUNUSED(str)) { return false; }
#endif
virtual bool Read(wxString& WXUNUSED(str)) { return false; }
// What type is it? Return a string name.
virtual wxString GetType() const = 0;
// If it based on wxObject return the ClassInfo.
virtual wxClassInfo* GetValueClassInfo() { return NULL; }
void IncRef() { m_count++; }
void DecRef()
{
if ( --m_count == 0 )
delete this;
}
int GetRefCount() const { return m_count; }
protected:
// Protected dtor should make some incompatible code
// break more louder. That is, they should do data->DecRef()
// instead of delete data.
virtual ~wxVariantData() { }
private:
int m_count;
private:
DECLARE_ABSTRACT_CLASS(wxVariantData)
};
/*
* wxVariant can store any kind of data, but has some basic types
* built in.
*/
class WXDLLIMPEXP_BASE wxVariant: public wxObject
{
public:
wxVariant();
wxVariant(const wxVariant& variant);
wxVariant(wxVariantData* data, const wxString& name = wxEmptyString);
virtual ~wxVariant();
// generic assignment
void operator= (const wxVariant& variant);
// Assignment using data, e.g.
// myVariant = new wxStringVariantData("hello");
void operator= (wxVariantData* variantData);
bool operator== (const wxVariant& variant) const;
bool operator!= (const wxVariant& variant) const;
// Sets/gets name
inline void SetName(const wxString& name) { m_name = name; }
inline const wxString& GetName() const { return m_name; }
// Tests whether there is data
bool IsNull() const;
// For compatibility with wxWidgets <= 2.6, this doesn't increase
// reference count.
wxVariantData* GetData() const { return m_data; }
void SetData(wxVariantData* data) ;
// make a 'clone' of the object
void Ref(const wxVariant& clone);
// destroy a reference
void UnRef();
// Make NULL (i.e. delete the data)
void MakeNull();
// Delete data and name
void Clear();
// Returns a string representing the type of the variant,
// e.g. "string", "bool", "stringlist", "list", "double", "long"
wxString GetType() const;
bool IsType(const wxString& type) const;
bool IsValueKindOf(const wxClassInfo* type) const;
// write contents to a string (e.g. for debugging)
wxString MakeString() const;
// double
wxVariant(double val, const wxString& name = wxEmptyString);
bool operator== (double value) const;
bool operator!= (double value) const;
void operator= (double value) ;
inline operator double () const { return GetDouble(); }
inline double GetReal() const { return GetDouble(); }
double GetDouble() const;
// long
wxVariant(long val, const wxString& name = wxEmptyString);
wxVariant(int val, const wxString& name = wxEmptyString);
wxVariant(short val, const wxString& name = wxEmptyString);
bool operator== (long value) const;
bool operator!= (long value) const;
void operator= (long value) ;
inline operator long () const { return GetLong(); }
inline long GetInteger() const { return GetLong(); }
long GetLong() const;
// bool
#ifdef HAVE_BOOL
wxVariant(bool val, const wxString& name = wxEmptyString);
bool operator== (bool value) const;
bool operator!= (bool value) const;
void operator= (bool value) ;
inline operator bool () const { return GetBool(); }
bool GetBool() const ;
#endif
// wxDateTime
#if wxUSE_DATETIME
wxVariant(const wxDateTime& val, const wxString& name = wxEmptyString);
#if wxUSE_ODBC
wxVariant(const DATE_STRUCT* valptr, const wxString& name = wxEmptyString);
wxVariant(const TIME_STRUCT* valptr, const wxString& name = wxEmptyString);
wxVariant(const TIMESTAMP_STRUCT* valptr, const wxString& name = wxEmptyString);
#endif
bool operator== (const wxDateTime& value) const;
bool operator!= (const wxDateTime& value) const;
void operator= (const wxDateTime& value) ;
#if wxUSE_ODBC
void operator= (const DATE_STRUCT* value) ;
void operator= (const TIME_STRUCT* value) ;
void operator= (const TIMESTAMP_STRUCT* value) ;
#endif
inline operator wxDateTime () const { return GetDateTime(); }
wxDateTime GetDateTime() const;
#endif
// wxString
wxVariant(const wxString& val, const wxString& name = wxEmptyString);
wxVariant(const wxChar* val, const wxString& name = wxEmptyString); // Necessary or VC++ assumes bool!
bool operator== (const wxString& value) const;
bool operator!= (const wxString& value) const;
void operator= (const wxString& value) ;
void operator= (const wxChar* value) ; // Necessary or VC++ assumes bool!
inline operator wxString () const { return MakeString(); }
wxString GetString() const;
// wxChar
wxVariant(wxChar val, const wxString& name = wxEmptyString);
bool operator== (wxChar value) const;
bool operator!= (wxChar value) const;
void operator= (wxChar value) ;
inline operator wxChar () const { return GetChar(); }
wxChar GetChar() const ;
// wxArrayString
wxVariant(const wxArrayString& val, const wxString& name = wxEmptyString);
bool operator== (const wxArrayString& value) const;
bool operator!= (const wxArrayString& value) const;
void operator= (const wxArrayString& value);
inline operator wxArrayString () const { return GetArrayString(); }
wxArrayString GetArrayString() const;
// void*
wxVariant(void* ptr, const wxString& name = wxEmptyString);
bool operator== (void* value) const;
bool operator!= (void* value) const;
void operator= (void* value);
inline operator void* () const { return GetVoidPtr(); }
void* GetVoidPtr() const;
// wxObject*
wxVariant(wxObject* ptr, const wxString& name = wxEmptyString);
bool operator== (wxObject* value) const;
bool operator!= (wxObject* value) const;
void operator= (wxObject* value);
wxObject* GetWxObjectPtr() const;
#if WXWIN_COMPATIBILITY_2_4
wxDEPRECATED( wxVariant(const wxStringList& val, const wxString& name = wxEmptyString) );
wxDEPRECATED( bool operator== (const wxStringList& value) const );
wxDEPRECATED( bool operator!= (const wxStringList& value) const );
wxDEPRECATED( void operator= (const wxStringList& value) );
wxDEPRECATED( wxStringList& GetStringList() const );
#endif
// ------------------------------
// list operations
// ------------------------------
wxVariant(const wxList& val, const wxString& name = wxEmptyString); // List of variants
bool operator== (const wxList& value) const;
bool operator!= (const wxList& value) const;
void operator= (const wxList& value) ;
// Treat a list variant as an array
wxVariant operator[] (size_t idx) const;
wxVariant& operator[] (size_t idx) ;
wxList& GetList() const ;
// Return the number of elements in a list
size_t GetCount() const;
// Make empty list
void NullList();
// Append to list
void Append(const wxVariant& value);
// Insert at front of list
void Insert(const wxVariant& value);
// Returns true if the variant is a member of the list
bool Member(const wxVariant& value) const;
// Deletes the nth element of the list
bool Delete(size_t item);
// Clear list
void ClearList();
public:
// Type conversion
bool Convert(long* value) const;
bool Convert(bool* value) const;
bool Convert(double* value) const;
bool Convert(wxString* value) const;
bool Convert(wxChar* value) const;
#if wxUSE_DATETIME
bool Convert(wxDateTime* value) const;
#endif // wxUSE_DATETIME
// Attributes
protected:
wxVariantData* m_data;
wxString m_name;
private:
DECLARE_DYNAMIC_CLASS(wxVariant)
};
#define DECLARE_VARIANT_OBJECT(classname) \
DECLARE_VARIANT_OBJECT_EXPORTED(classname, wxEMPTY_PARAMETER_VALUE)
#define DECLARE_VARIANT_OBJECT_EXPORTED(classname,expdecl) \
expdecl classname& operator << ( classname &object, const wxVariant &variant ); \
expdecl wxVariant& operator << ( wxVariant &variant, const classname &object );
#define IMPLEMENT_VARIANT_OBJECT(classname) \
IMPLEMENT_VARIANT_OBJECT_EXPORTED(classname, wxEMPTY_PARAMETER_VALUE)
#define IMPLEMENT_VARIANT_OBJECT_EXPORTED_NO_EQ(classname,expdecl) \
class classname##VariantData: public wxVariantData \
{ \
public:\
classname##VariantData() {} \
classname##VariantData( const classname &value ) { m_value = value; } \
\
classname &GetValue() { return m_value; } \
\
virtual bool Eq(wxVariantData& data) const; \
\
virtual wxString GetType() const; \
virtual wxClassInfo* GetValueClassInfo(); \
\
protected:\
classname m_value; \
\
private: \
DECLARE_CLASS(classname##VariantData) \
};\
\
IMPLEMENT_CLASS(classname##VariantData, wxVariantData)\
\
wxString classname##VariantData::GetType() const\
{\
return m_value.GetClassInfo()->GetClassName();\
}\
\
wxClassInfo* classname##VariantData::GetValueClassInfo()\
{\
return m_value.GetClassInfo();\
}\
\
expdecl classname& operator << ( classname &value, const wxVariant &variant )\
{\
wxASSERT( wxIsKindOf( variant.GetData(), classname##VariantData ) );\
\
classname##VariantData *data = (classname##VariantData*) variant.GetData();\
value = data->GetValue();\
return value;\
}\
\
expdecl wxVariant& operator << ( wxVariant &variant, const classname &value )\
{\
classname##VariantData *data = new classname##VariantData( value );\
variant.SetData( data );\
return variant;\
}
// implements a wxVariantData-derived class using for the Eq() method the
// operator== which must have been provided by "classname"
#define IMPLEMENT_VARIANT_OBJECT_EXPORTED(classname,expdecl) \
IMPLEMENT_VARIANT_OBJECT_EXPORTED_NO_EQ(classname,wxEMPTY_PARAMETER_VALUE expdecl) \
\
bool classname##VariantData::Eq(wxVariantData& data) const \
{\
wxASSERT( wxIsKindOf((&data), classname##VariantData) );\
\
classname##VariantData & otherData = (classname##VariantData &) data;\
\
return otherData.m_value == m_value;\
}\
// implements a wxVariantData-derived class using for the Eq() method a shallow
// comparison (through wxObject::IsSameAs function)
#define IMPLEMENT_VARIANT_OBJECT_SHALLOWCMP(classname) \
IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(classname, wxEMPTY_PARAMETER_VALUE)
#define IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(classname,expdecl) \
IMPLEMENT_VARIANT_OBJECT_EXPORTED_NO_EQ(classname,wxEMPTY_PARAMETER_VALUE expdecl) \
\
bool classname##VariantData::Eq(wxVariantData& data) const \
{\
wxASSERT( wxIsKindOf((&data), classname##VariantData) );\
\
classname##VariantData & otherData = (classname##VariantData &) data;\
\
return (otherData.m_value.IsSameAs(m_value));\
}\
// Since we want type safety wxVariant we need to fetch and dynamic_cast
// in a seemingly safe way so the compiler can check, so we define
// a dynamic_cast /wxDynamicCast analogue.
#define wxGetVariantCast(var,classname) \
((classname*)(var.IsValueKindOf(&classname::ms_classInfo) ?\
var.GetWxObjectPtr() : NULL));
extern wxVariant WXDLLIMPEXP_BASE wxNullVariant;
#endif // _WX_VARIANT_H_
| [
"[email protected]"
] | [
[
[
1,
422
]
]
] |
050071f2785be2660a2f2b60f75f39b83ac164ce | c6f4fe2766815616b37beccf07db82c0da27e6c1 | /Texture.cpp | ea65ed439bd0a6988e4abb51f79f35b2a1cbd780 | [] | no_license | fragoulis/gpm-sem1-spacegame | c600f300046c054f7ab3cbf7193ccaad1503ca09 | 85bdfb5b62e2964588f41d03a295b2431ff9689f | refs/heads/master | 2023-06-09T03:43:53.175249 | 2007-12-13T03:03:30 | 2007-12-13T03:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | #include "Texture.h"
#include "gx/Image.h"
#include "Logger.h"
using gxbase::Image;
namespace tlib
{
OCTexture::OCTexture() {}
OCTexture::OCTexture( const char *filename ) {
load( filename );
}
bool OCTexture::load( const char *filename )
{
_LOG("Loading texture " + string(filename));
Image image;
// Load image file
if( !image.Load( filename ) )
{
_LOG("Failed to load texture");
image.Free();
return false;
}
// Generate texture
glGenTextures( 1, &m_TexId );
// Generate mipmaps and free image from memory
glBindTexture( GL_TEXTURE_2D, m_TexId );
image.gluBuild2DMipmaps();
image.Free();
return true;
}
} // end of namespace tlib | [
"john.fragkoulis@201bd241-053d-0410-948a-418211174e54"
] | [
[
[
1,
37
]
]
] |
41f306e46c3330b8d8fabf02d3c1c420245b3bda | 6dfee96a4a2fd190321b37f757a04d6039e365be | /Weibo.sdk/WBParseWrapper/wbParseObj.cpp | a0edcc433772546670977373be016948e00063bf | [] | no_license | skyui-cdel/MyFirstGit | 4d0172e9058f2dbc54c8fe1f9a142ed7e262b977 | 9f62707e7a0624767c36e99038268a4dd2cb4791 | refs/heads/master | 2018-12-28T00:01:42.206089 | 2011-05-27T05:37:23 | 2011-05-27T05:37:23 | 2,252,774 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 47,206 | cpp | /**
* @brief analysis object,
* @file WeiboParsObj.cpp
* @author welbon
* @Email < [email protected] >
*
* Copyright (C) 1996-2010 SINA Corporation, All Rights Reserved
*
* 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 "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <json/json.h>
#include "wbParseObj.h"
#include "wbParseMalloc.h"
#include "splitstr.h"
#include "wbParseMacro.h"
#include "strconv.h"
using namespace wbParserNS ;
// DATA KEY
#define WBPARSER_KEY_IDX(name) WBParser_##name##_KEY
#define WBPARSER_KEY_STATEIDX(name) WBParser_state_##name##_KEY
#define WBPARSER_KEY_USERIDX(name) WBParser_user_##name##_KEY
#define WBPARSER_KEY_COMMENTIDX(name) WBParser_comment_##name##_KEY
#define WBPARSER_KEY_DIRMSGIDX(name) WBParser_directmsg_##name##_KEY
#define WBPARSER_KEY_GEO(name) WBParser_geo_##name##_KEY
#define WBPARSER_KEY_UREADER(name) WBParser_unreader_##name##_KEY
#define WBPARSER_KEY_COMCOUNT(name) WBParser_comcount_##name##_KEY
#define WBPARSER_KEY_ACCESS_LMT(name) WBParser_accesslmt_##name##_KEY
#define WBPARSER_KEY_EMOTION(name) WBParser_emotion##name##_KEY
#define WBPARSER_KEY_XMLROOT(name) WBParser_xmlroot_##name##KEY
/////////////////////////
//关键字定义
typedef enum
{
// ptr
WBPARSER_KEY_STATEIDX(createtime),
WBPARSER_KEY_STATEIDX(id),
WBPARSER_KEY_STATEIDX(text),
WBPARSER_KEY_STATEIDX(source),
WBPARSER_KEY_STATEIDX(favorited),
WBPARSER_KEY_STATEIDX(truncated),
WBPARSER_KEY_STATEIDX(rsid),
WBPARSER_KEY_STATEIDX(ruid),
WBPARSER_KEY_STATEIDX(rtsname),
WBPARSER_KEY_STATEIDX(thumbpic),
WBPARSER_KEY_STATEIDX(midpic),
WBPARSER_KEY_STATEIDX(originpic),
WBPARSER_KEY_STATEIDX(geo),
WBPARSER_KEY_STATEIDX(user),
WBPARSER_KEY_STATEIDX(retstatus),
// users
WBPARSER_KEY_USERIDX(id),
WBPARSER_KEY_USERIDX(scname),
WBPARSER_KEY_USERIDX(name),
WBPARSER_KEY_USERIDX(province),
WBPARSER_KEY_USERIDX(city),
WBPARSER_KEY_USERIDX(location),
WBPARSER_KEY_USERIDX(description),
WBPARSER_KEY_USERIDX(url),
WBPARSER_KEY_USERIDX(prourl),
WBPARSER_KEY_USERIDX(domain),
WBPARSER_KEY_USERIDX(gender),
WBPARSER_KEY_USERIDX(followcount),
WBPARSER_KEY_USERIDX(frcount),
WBPARSER_KEY_USERIDX(stacount),
WBPARSER_KEY_USERIDX(favcount),
WBPARSER_KEY_USERIDX(allowall),
WBPARSER_KEY_USERIDX(geoenable),
WBPARSER_KEY_USERIDX(createdat),
WBPARSER_KEY_USERIDX(following),
WBPARSER_KEY_USERIDX(verified),
WBPARSER_KEY_USERIDX(last_status),
// comments
WBPARSER_KEY_COMMENTIDX(id),
WBPARSER_KEY_COMMENTIDX(text),
WBPARSER_KEY_COMMENTIDX(source),
WBPARSER_KEY_COMMENTIDX(favorited),
WBPARSER_KEY_COMMENTIDX(truncated),
WBPARSER_KEY_COMMENTIDX(createdat),
WBPARSER_KEY_COMMENTIDX(user),
WBPARSER_KEY_COMMENTIDX(status),
WBPARSER_KEY_COMMENTIDX(rcomment),
// direct message
WBPARSER_KEY_DIRMSGIDX(id),
WBPARSER_KEY_DIRMSGIDX(text),
WBPARSER_KEY_DIRMSGIDX(senderid),
WBPARSER_KEY_DIRMSGIDX(recipientid),
WBPARSER_KEY_DIRMSGIDX(createdat),
WBPARSER_KEY_DIRMSGIDX(sndsname),
WBPARSER_KEY_DIRMSGIDX(rsnsame),
WBPARSER_KEY_DIRMSGIDX(sender),
WBPARSER_KEY_DIRMSGIDX(recipient),
// geo
WBPARSER_KEY_GEO(type),
WBPARSER_KEY_GEO(coordinates),
// 评论计数
WBPARSER_KEY_COMCOUNT(id),
WBPARSER_KEY_COMCOUNT(comments),
WBPARSER_KEY_COMCOUNT(rt),
// unreader
WBPARSER_KEY_UREADER(comments),
WBPARSER_KEY_UREADER(mentions),
WBPARSER_KEY_UREADER(dm),
WBPARSER_KEY_UREADER(followers),
WBPARSER_KEY_UREADER(new_status),
// ACCES limite
WBPARSER_KEY_ACCESS_LMT(hourlimit),
WBPARSER_KEY_ACCESS_LMT(rstimeinseond),
WBPARSER_KEY_ACCESS_LMT(remaining_hits),
WBPARSER_KEY_ACCESS_LMT(reset_time),
//Emotion
WBPARSER_KEY_EMOTION(phrase),
WBPARSER_KEY_EMOTION(type),
WBPARSER_KEY_EMOTION(url),
WBPARSER_KEY_EMOTION(is_hot),
WBPARSER_KEY_EMOTION(is_common),
WBPARSER_KEY_EMOTION(order_number),
WBPARSER_KEY_EMOTION(category),
// 分页
WBPARSER_KEY_IDX(next_cursor),
WBPARSER_KEY_IDX(previous_cursor),
// XML ROOT KEYS
WBPARSER_KEY_XMLROOT(statuses),
WBPARSER_KEY_XMLROOT(status),
WBPARSER_KEY_IDX(end),
}key_index;
static
const WBParseCHAR* weibo_key_array[] =
{
// ptr
_WBC("created_at"),
_WBC("id"),
_WBC("text"),
_WBC("source"),
_WBC("favorited"),
_WBC("truncated"),
_WBC("in_reply_to_status_id"),
_WBC("in_reply_to_user_id"),
_WBC("in_reply_to_screen_name"),
_WBC("thumbnail_pic"),
_WBC("bmiddle_pic"),
_WBC("original_pic"),
_WBC("geo"),
_WBC("user"),
_WBC("retweeted_status"),
// users
_WBC("id"),
_WBC("screen_name"),
_WBC("name"),
_WBC("province"),
_WBC("city"),
_WBC("location"),
_WBC("description"),
_WBC("url"),
_WBC("profile_image_url"),
_WBC("domain"),
_WBC("gender"),
_WBC("followers_count"),
_WBC("friends_count"),
_WBC("statuses_count"),
_WBC("favourites_count"),
_WBC("allow_all_act_msg"),
_WBC("geo_enabled"),
_WBC("created_at"),
_WBC("following"),
_WBC("verified"),
_WBC("status"),
// comments
_WBC("id"),
_WBC("text"),
_WBC("source"),
_WBC("favorited"),
_WBC("truncated"),
_WBC("created_at"),
_WBC("user"),
_WBC("status"),
_WBC("reply_comment"),
// direct message
_WBC("id"),
_WBC("text"),
_WBC("sender_id"),
_WBC("recipient_id"),
_WBC("created_at"),
_WBC("sender_screen_name"),
_WBC("recipient_screen_name"),
_WBC("sender"),
_WBC("recipient"),
// geo
_WBC("type"),
_WBC("coordinates"),
// 评论计数
_WBC("id"),
_WBC("comments"),
_WBC("rt"),
//未读消息数
_WBC("comments"),
_WBC("mentions"),
_WBC("dm"),
_WBC("followers"),
_WBC("new_status"),
// 访问限制
_WBC("hourly_limit"),
_WBC("reset_time_in_seconds"),
_WBC("remaining_hits"),
_WBC("reset_time"),
//Emotion
_WBC("phrase"),
_WBC("type"),
_WBC("url"),
_WBC("is_hot"),
_WBC("is_common"),
_WBC("order_number"),
_WBC("category"),
// 分页
_WBC("next_cursor"),
_WBC("previous_cursor"),
//
// XML ROOT KEYS
_WBC("statuses"),
_WBC("status"),
};
const WBParseCHAR* wbParse_GetKey(int idx)
{
if( idx >= WBPARSER_KEY_IDX(end) ||
idx < 0 )
{
return 0;
}
return weibo_key_array[idx];
}
#define GET_VALUEKEY(idx) wbParse_GetKey(idx)
#define WEIBO_PARSER_CAST(t,ptr) (t*)ptr
#if defined(_USE_JSON_PARSER)
/** 解析状态 */
t_wbParse_Status *CWBJsonParser::parse_status(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Status* ptr = 0;
if( obj)
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Status,wbParse_Malloc_Status(1));
parse_status(obj, ptr);
}
return ptr;
}
void CWBJsonParser::parse_status(wbParserNS::REQOBJ *obj , t_wbParse_Status * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// created_at
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(createtime)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
// text
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(text)),ptr->text,WBPARSER_USE_LEN(text) );
// source
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(source)),ptr->source,WBPARSER_USE_LEN(source) );
// in_reply_to_status_id
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(rsid)),ptr->in_reply_to_status_id,WBPARSER_USE_LEN(in_reply_to_status_id) );
// in_reply_to_screen_name
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(rtsname)),ptr->in_reply_to_screen_name,WBPARSER_USE_LEN(in_reply_to_screen_name) );
// thumbnail_pic
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(thumbpic)),ptr->thumbnail_pic,WBPARSER_USE_LEN(thumbnail_pic) );
// bmiddle_pic
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(midpic)),ptr->bmiddle_pic,WBPARSER_USE_LEN(bmiddle_pic) );
// original_pic
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(originpic)),ptr->original_pic,WBPARSER_USE_LEN(original_pic) );
// favorited
GET_BOOL(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(favorited)),ptr->favorited );
// truncated
GET_BOOL(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(truncated)),ptr->truncated );
//
USE_WEIBOPARSE_OBJ_PTR ;
// geo
GET_OBJECT(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(geo)),ptr->geo,parse_geo);
// user
GET_OBJECT(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(user)),ptr->user,parse_user);
// retweeted_status
GET_OBJECT(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(retstatus)),ptr->retweeted_status,parse_status);
}
struct t_wbParse_Error* CWBJsonParser::parse_error(wbParserNS::REQOBJ *obj)
{
t_wbParse_Error* ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Error,wbParse_Malloc_Error(1) );
parse_error(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_error(wbParserNS::REQOBJ *obj , t_wbParse_Error * ptr)
{
if( !ptr || !obj )
return ;
int len = 0;
const char* txt = NULL;
//
//txt = wbParserNS::GetCHAR_Key_XML_EX("request" , obj , len );
GET_STR_EX(JSON,obj,"request",txt,len );
if( len && txt ) {
strncpy( ptr->request ,txt , WBPARSER_USE_LEN(request) );
}
//txt = wbParserNS::GetCHAR_Key_JSON_EX("error_code" , obj, len);
GET_STR_EX(JSON,obj,"error_code",txt,len);
if( len && txt ) {
strncpy( ptr->error_code,txt , WBPARSER_USE_LEN(error_code) );
}
//txt = wbParserNS::GetCHAR_Key_JSON_EX("error" , obj, len);
GET_STR_EX(JSON,obj,"error",txt,len);
if( len && txt ) {
strncpy( ptr->error,txt,WBPARSER_USE_LEN(error) );
ptr->error_sub_code = atoi(ptr->error);
}
}
/** 解析用户 */
t_wbParse_User *CWBJsonParser::parse_user(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_User* ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_User,wbParse_Malloc_User(1));
parse_user(obj, ptr );
}
return ptr;
}
void CWBJsonParser::parse_user(wbParserNS::REQOBJ *obj , t_wbParse_User * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// screen_name
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(name)),ptr->screen_name,WBPARSER_USE_LEN(screen_name) );
// name
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(name)),ptr->name,WBPARSER_USE_LEN(name) );
// province
GET_LONG_TO_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(province)),ptr->province,WBPARSER_USE_LEN(province) );
// city
GET_LONG_TO_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(city)),ptr->city,WBPARSER_USE_LEN(city) );
// location
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(location)),ptr->location,WBPARSER_USE_LEN(location) );
// description
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(description)),ptr->description,WBPARSER_USE_LEN(description) );
// url
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(url)),ptr->url,WBPARSER_USE_LEN(url) );
// profile_image_url
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(prourl)),ptr->profile_image_url,WBPARSER_USE_LEN(profile_image_url) );
// domain
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(domain)),ptr->domain,WBPARSER_USE_LEN(domain) );
// gender
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(gender)),ptr->gender,WBPARSER_USE_LEN(gender) );
// created_at
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(createdat)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
// followers_count
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(followcount)),ptr->followers_count );
// followers_count
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(frcount)),ptr->friends_count );
// statuses_count
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(stacount)),ptr->statuses_count );
// favourites_count
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(favcount)),ptr->favourites_count );
// allow_all_act_msg
GET_BOOL(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(allowall)),ptr->allow_all_act_msg );
// geo_enabled
GET_BOOL(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(geoenable)),ptr->geo_enabled );
// following
GET_BOOL(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(following)),ptr->following );
// following
GET_BOOL(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(verified)),ptr->verified );
// last status
USE_WEIBOPARSE_OBJ_PTR;
GET_OBJECT(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(last_status)),ptr->last_status,parse_status);
}
/** 解析地理位置 */
t_wbParse_Geo *CWBJsonParser::parse_geo(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Geo *ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Geo,wbParse_Malloc_Geo(1));
parse_geo(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_geo(wbParserNS::REQOBJ *obj , t_wbParse_Geo * ptr)
{
if( !ptr || !obj )
return ;
//
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_GEO(type)),ptr->type,WBPARSER_USE_LEN(type)) ;
//
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_GEO(coordinates)),ptr->coordinates,WBPARSER_USE_LEN(coordinates)) ;
}
/** 解析评论 */
t_wbParse_Comment *CWBJsonParser::parse_comment(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Comment *ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Comment,wbParse_Malloc_Comment(1));
parse_comment(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_comment(wbParserNS::REQOBJ *obj , t_wbParse_Comment * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// text
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(text)),ptr->text,WBPARSER_USE_LEN(text) );
// source
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(source)),ptr->source,WBPARSER_USE_LEN(source) );
// favorited
GET_BOOL(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(favorited)),ptr->favorited );
// created_at
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(createdat)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
//
USE_WEIBOPARSE_OBJ_PTR ;
// user
GET_OBJECT(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(user)),ptr->user,parse_user);
// status
GET_OBJECT(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(status)),ptr->status,parse_status);
// reply_comment
GET_OBJECT(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(rcomment)),ptr->reply_comment,parse_comment);
}
/** 私信 */
t_wbParse_DirectMessage *CWBJsonParser::parse_directmessage(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_DirectMessage* ptr =0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_DirectMessage,wbParse_Malloc_Directmessage(1));
parse_directmessage(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_directmessage(wbParserNS::REQOBJ *obj , t_wbParse_DirectMessage * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// text
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(text)),ptr->text,WBPARSER_USE_LEN(text) );
// created_at
GET_STR(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(createdat)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
// sender_id
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(senderid)),ptr->sender_id,WBPARSER_USE_LEN(id) );
// recipient_id
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(recipientid)),ptr->recipient_id,WBPARSER_USE_LEN(id) );
// sender_screen_name
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(sndsname)),ptr->sender_screen_name,WBPARSER_USE_LEN(name) );
//recipient_screen_name
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(rsnsame)),ptr->recipient_screen_name,WBPARSER_USE_LEN(name) );
//
USE_WEIBOPARSE_OBJ_PTR ;
//sender
GET_OBJECT( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(sender)),ptr->sender,parse_user );
//recipient
GET_OBJECT( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(recipient)),ptr->recipient,parse_user );
}
/** 解析未读数 */
t_wbParse_Unread *CWBJsonParser::parse_unread(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Unread *ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Unread,wbParse_Malloc_Unread(1));
parse_unread(obj ,ptr );
}
return ptr;
}
void CWBJsonParser::parse_unread(wbParserNS::REQOBJ *obj , t_wbParse_Unread * ptr)
{
if( !ptr || !obj )
return ;
// comments
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(comments)),ptr->comments);
// mentions
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(mentions)),ptr->mentions);
// dm
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(dm)),ptr->dm);
// followers
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(followers)),ptr->followers);
GET_LONG(JSON,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(new_status)),ptr->new_status);
}
/** 解析评论计数 */
t_wbParse_CommentCounts *CWBJsonParser::parse_commentcounts(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_CommentCounts *ptr = 0;
if( obj)
{
ptr = WEIBO_PARSER_CAST(t_wbParse_CommentCounts,wbParse_Malloc_Commentcount(1));
parse_commentcounts(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_commentcounts(wbParserNS::REQOBJ *obj , t_wbParse_CommentCounts * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMCOUNT(id)),ptr->id,WBPARSER_USE_LEN(id) );
// comments
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMCOUNT(comments)),ptr->comments );
// rt
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_COMCOUNT(rt)),ptr->rt );
}
t_wbParse_LimitStatus *CWBJsonParser::parse_limite_status(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_LimitStatus *ptr = 0;
if( obj)
{
ptr = (t_wbParse_LimitStatus *)wbParse_Malloc_Limits(1);
parse_limite_status(obj , ptr);
}
return ptr;
}
void CWBJsonParser::parse_limite_status(wbParserNS::REQOBJ *obj , t_wbParse_LimitStatus * ptr)
{
if( !ptr || !obj )
return ;
// hourly_limit
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(hourlimit)),ptr->hourly_limit );
// rstimeinseond
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(rstimeinseond)),ptr->reset_time_in_seconds );
// remaining_hits
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(remaining_hits)),ptr->remaining_hits );
// reset_time
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(reset_time)),ptr->reset_time,WBPARSER_USE_LEN(reset_time) );
}
t_wbParse_Emotion *CWBJsonParser::parse_emotion(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Emotion *ptr = 0;
if( obj )
{
ptr = (t_wbParse_Emotion *)wbParse_Malloc_Emotion(1);
parse_emotion(obj , ptr);
}
return ptr;
}
void CWBJsonParser::parse_emotion(wbParserNS::REQOBJ *obj , t_wbParse_Emotion * ptr)
{
if( !ptr || !obj )
return ;
// phrase
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(phrase)),ptr->phrase,WBPARSER_USE_LEN(phrase) );
// type
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(type)),ptr->type,WBPARSER_USE_LEN(type) );
// url
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(url)),ptr->url,WBPARSER_USE_LEN(url) );
//category
GET_STR( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(category)),ptr->category,WBPARSER_USE_LEN(category) );
// is_hot
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(is_hot)),ptr->is_hot );
// is_common
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(is_common)),ptr->is_common );
// order_number
GET_LONG( JSON,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(order_number)),ptr->order_number );
}
t_wbParse_Shipshow *CWBJsonParser::parse_shipshow(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Shipshow *ptr = 0;
if( obj )
{
ptr = (t_wbParse_Shipshow *)wbParse_Malloc_Friendship(1);
parse_shipshow(obj , ptr);
}
return ptr;
}
void CWBJsonParser::parse_shipshow(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Shipshow *ptr)
{
//{
// "source":{
// "id":245110499
// ,"screen_name":"245110499"
// ,"following":false
// ,"followed_by":false
// ,"notifications_enabled":false
// }
// ,"target":{
// "id":10503
// ,"screen_name":"10503"
// ,"following":false
// ,"followed_by":false
// ,"notifications_enabled":false
// }
//}
if( !ptr || !obj )
return ;
//
USE_WEIBOPARSE_OBJ_PTR ;
//source
GET_OBJECT( JSON,obj,"source",ptr->source,parse_ship_item );
//source
GET_OBJECT( JSON,obj,"target",ptr->target,parse_ship_item );
}
t_wbParse_Shipshow::Item* CWBJsonParser::parse_ship_item(wbParserNS::REQOBJ *obj)
{
// "source":{
// "id":245110499
// ,"screen_name":"245110499"
// ,"following":false
// ,"followed_by":false
// ,"notifications_enabled":false
// }
if( !obj )
return 0;
t_wbParse_Shipshow::Item* ptr = (t_wbParse_Shipshow::Item*)malloc(sizeof(t_wbParse_Shipshow::Item));
memset(ptr , 0 , sizeof(t_wbParse_Shipshow::Item));
// id
GET_LONG_TO_STR( JSON,obj,"id",ptr->id,WBPARSER_USE_LEN(id) );
// screen_name
GET_STR( JSON,obj,"screen_name",ptr->screen_name,WBPARSER_USE_LEN(screen_name) );
// following
GET_LONG( JSON,obj,"following",ptr->following);
// following
GET_LONG( JSON,obj,"followed_by",ptr->followed_by);
// following
GET_LONG( JSON,obj,"notifications_enabled",ptr->notifications_enabled);
return ptr;
}
/** 邀请联系人用户 */
t_wbParse_InviteContact::ItemUsr *CWBJsonParser::parse_invite_contact_usr(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_InviteContact::ItemUsr *ptr = 0;
if( obj ) {
ptr = (t_wbParse_InviteContact::ItemUsr*)wbParse_Malloc_InviteContact_Usr(1);
parse_invite_contact_usr(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_invite_contact_usr(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_InviteContact::ItemUsr *ptr)
{
if( !ptr || !obj )
return ;
// UID
GET_STR( JSON,obj,"uid",ptr->uid_,WBPARSER_USE_LEN(id) );
// NAME
GET_STR( JSON,obj,"name",ptr->name_,WBPARSER_USE_LEN(screen_name) );
char* outstr = NULL;
if( lo_Utf82C(&outstr , ptr->name_) ) {
strcpy( ptr->name_,outstr );
free(outstr);
}
// URL
GET_STR( JSON,obj,"icon",ptr->iconurl_,WBPARSER_USE_LEN(url) );
// EMAIL
GET_STR( JSON,obj,"email",ptr->email_,WBPARSER_USE_LEN(email) );
}
/** 用户标签 */
t_wbParse_Tag *CWBJsonParser::parse_Tags(/*[in]*/wbParserNS::REQOBJ *obj,WBParseCHAR *idKey )
{
t_wbParse_Tag *ptr = 0;
if( obj ) {
ptr = (t_wbParse_Tag*)wbParse_Malloc_Tag(1);
parse_Tags(obj,ptr,idKey );
}
return ptr;
}
void CWBJsonParser::parse_Tags(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Tag *ptr,WBParseCHAR *idKey )
{
if( !ptr || !obj )
return ;
Json::Value *val = (Json::Value*)obj;
if( idKey && *idKey != '\0' )
{
std::basic_string<WBParseCHAR> cc;
// tag id
Json::Value &jvalTagID = ((*val)[idKey]);
(jvalTagID.isString()) ? (cc = (jvalTagID.asString())) : 0;
if( !cc.empty()){
WBPARSER_COPY( ptr->tagId_,WBPARSER_REAL_LEN(TAGS_ID),cc.c_str(),cc.length() );
}
// tag name
Json::Value &jvalTagName = ((*val)["value"]);
( jvalTagName.isString()) ? (cc = (jvalTagName.asString())) : (0);
if( cc.length()){
WBPARSER_COPY(ptr->tagName_,WBPARSER_REAL_LEN(TAGS_ID),cc.c_str(),cc.length() );
}
}
else {
Json::Value::iterator it_begin = val->begin() ;
// tag name
WBPARSER_COPY(ptr->tagId_,WBPARSER_REAL_LEN(TAGS_ID),it_begin.memberName(),strlen(it_begin.memberName()));
// tag id
WBPARSER_COPY(ptr->tagName_,WBPARSER_REAL_LEN(TAGS_NAME),(*it_begin).asString().c_str(),(*it_begin).asString().length() );
}
}
/** 话题 */
t_wbParse_Trend *CWBJsonParser::parse_Trends_getData(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Trend *ptr = 0;
if( obj ) {
ptr = (t_wbParse_Trend*)wbParse_Malloc_Trend(1);
parse_Trends_getData(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_Trends_getData(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Trend *ptr)
{
if( !ptr || !obj )
return ;
//
GET_STR( JSON,obj,"trend_id",ptr->trendId_ ,WBPARSER_USE_LEN(TREND_ID) );
GET_STR( JSON,obj,"hotword" ,ptr->trendHotword_,WBPARSER_USE_LEN(TREND_NAME) );
GET_STR( JSON,obj,"num" ,ptr->trendNumber_ ,WBPARSER_USE_LEN(TREND_ID) );
}
//follow
t_wbParse_Trend *CWBJsonParser::parse_Trends_Follow(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Trend *ptr = 0;
if( obj ) {
ptr = (t_wbParse_Trend*)wbParse_Malloc_Trend(1);
parse_Trends_Follow(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_Trends_Follow(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Trend *ptr)
{
if( !ptr || !obj )
return ;
GET_STR( JSON,obj,"topicid",ptr->trendId_,WBPARSER_USE_LEN(TREND_ID) );
}
// hot
t_wbParse_TrendHotQuery::TrendItem *CWBJsonParser::parse_Trends_getHot(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_TrendHotQuery::TrendItem *ptr = 0;
if( obj ) {
ptr = (t_wbParse_TrendHotQuery::TrendItem*)wbParse_Malloc_TrendHotQuery_Item(1);
parse_Trends_getHot(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_Trends_getHot(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_TrendHotQuery::TrendItem *ptr)
{
if( !ptr || !obj )
return ;
// name
GET_STR( JSON,obj,"name",ptr->trendName_,WBPARSER_USE_LEN(TREND_NAME) );
//
GET_STR( JSON,obj,"query",ptr->trendQuery_,WBPARSER_USE_LEN(TREND_NAME) );
}
/** 一个结果 */
t_wbParse_Ret *CWBJsonParser::parse_Ret(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Ret *ptr = 0;
if( obj ) {
ptr = (t_wbParse_Ret*)wbParse_Malloc_Ret(1);
parse_Ret(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_Ret(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Ret *ptr)
{
if( !ptr || !obj )
return ;
// 错误码
GET_STR_IDX( JSON,obj,0,ptr->error_code_,WBPARSER_REAL_LEN(error_code));
}
#ifdef _USE_GET_SHORTURL_BATCH
// media shorturl batch
t_wbParse_Media_ShortUrlBatch *CWBJsonParser::parse_Media_ShortURLBatch(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Media_ShortUrlBatch *ptr = 0;
if( obj ) {
ptr = (t_wbParse_Media_ShortUrlBatch*)wbParse_Malloc_Ret(1);
parse_Media_ShortURLBatch(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_Media_ShortURLBatch(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Media_ShortUrlBatch *ptr )
{
if( !ptr || !obj )
return ;
// short url
GET_STR( JSON,obj,"url_short",ptr->urlshort_,WBPARSER_USE_LEN(url) );
// long url
GET_STR( JSON,obj,"url_long",ptr->urllong_,WBPARSER_USE_LEN(url) );
// type
GET_LONG( JSON,obj,"type",ptr->type_ );
// title
GET_STR( JSON,obj,"title",ptr->title_,WBPARSER_REAL_LEN(name) );
// description
GET_STR( JSON,obj,"description",ptr->description_,WBPARSER_REAL_LEN(text) );
// last_modified
GET_STR( JSON,obj,"last_modified",ptr->lastmodified_,WBPARSER_REAL_LEN(created_at));
// object anni
wbParserNS::REQOBJ *pObjAnni = wbParserNS::GetObject_Key_JSON("annotations",obj) ;
if( !pObjAnni){
return ;
}
//
GET_OBJECT_SIZE( JSON,pObjAnni,ptr->anCounts_);
//
if( 0 < ptr->anCounts_){
typedef t_wbParse_Media_ShortUrlBatch::ItemAnnotions ItemAnnotions;
ItemAnnotions* pAnniList = (ItemAnnotions*)wbParse_Malloc_Media_ShortURLBatch_ItemAnnotions(ptr->anCounts_);
for( int i = 0 ; i < ptr->anCounts_ ; ++ i ) {
ItemAnnotions* pAnni = (pAnniList + i);
parse_Media_ShortURLBatch_ItemAnnotions(pObjAnni,pAnni);
}
ptr->annotions_ = pAnniList;
}
}
// media shorturl batch annotions
t_wbParse_Media_ShortUrlBatch::ItemAnnotions *CWBJsonParser::parse_Media_ShortURLBatch_ItemAnnotions(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Media_ShortUrlBatch::ItemAnnotions *ptr = 0;
if( obj ) {
ptr = (t_wbParse_Media_ShortUrlBatch::ItemAnnotions *)wbParse_Malloc_Ret(1);
parse_Media_ShortURLBatch_ItemAnnotions(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_Media_ShortURLBatch_ItemAnnotions(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Media_ShortUrlBatch::ItemAnnotions *ptr)
{
if( !ptr || !obj )
return ;
// url
GET_STR( JSON,obj,"url",ptr->url,WBPARSER_USE_LEN(url) );
// pic url
GET_STR( JSON,obj,"pic",ptr->pic,WBPARSER_USE_LEN(url) );
// from
GET_LONG( JSON,obj,"from",ptr->from );
// title
GET_STR( JSON,obj,"title",ptr->title,WBPARSER_REAL_LEN(name) );
}
#endif //#ifdef _USE_GET_SHORTURL_BATCH
t_wbParse_UploadPic *CWBJsonParser::parse_UploadPic(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_UploadPic *ptr = 0;
if( obj ) {
ptr = (t_wbParse_UploadPic*)wbParse_Malloc_Ret(1);
parse_UploadPic(obj,ptr);
}
return ptr;
}
void CWBJsonParser::parse_UploadPic(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_UploadPic *ptr)
{
if( !ptr || !obj )
return ;
// pic_id
GET_STR( JSON,obj,"pic_id",ptr->pic_id,WBPARSER_USE_LEN(url) );
// thumbnail_pic
GET_STR( JSON,obj,"thumbnail_pic",ptr->thumbnail_pic,WBPARSER_USE_LEN(url) );
// bmiddle_pic
GET_STR( JSON,obj,"bmiddle_pic",ptr->bmiddle_pic,WBPARSER_USE_LEN(url) );
// original_pic
GET_STR( JSON,obj,"original_pic",ptr->original_pic,WBPARSER_REAL_LEN(name) );
}
#endif //#if defined(_USE_JSON_PARSER)
#if defined(_USE_XML_PARSER)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// XML 解析
/** 解析状态 */
t_wbParse_Status *CWBXmlParser::parse_status(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Status* ptr = 0;
if( obj)
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Status,wbParse_Malloc_Status(1));
parse_status(obj, ptr);
}
return ptr;
}
void CWBXmlParser::parse_status(wbParserNS::REQOBJ *obj , t_wbParse_Status * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// created_at
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(createtime)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
// text
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(text)),ptr->text,WBPARSER_USE_LEN(text) );
// source
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(source)),ptr->source,WBPARSER_USE_LEN(source) );
// in_reply_to_status_id
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(rsid)),ptr->in_reply_to_status_id,WBPARSER_USE_LEN(in_reply_to_status_id) );
// in_reply_to_screen_name
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(rtsname)),ptr->in_reply_to_screen_name,WBPARSER_USE_LEN(in_reply_to_screen_name) );
// thumbnail_pic
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(thumbpic)),ptr->thumbnail_pic,WBPARSER_USE_LEN(thumbnail_pic) );
// bmiddle_pic
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(midpic)),ptr->bmiddle_pic,WBPARSER_USE_LEN(bmiddle_pic) );
// original_pic
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(originpic)),ptr->original_pic,WBPARSER_USE_LEN(original_pic) );
// favorited
GET_BOOL(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(favorited)),ptr->favorited );
// truncated
GET_BOOL(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(truncated)),ptr->truncated );
//
USE_WEIBOPARSE_OBJ_PTR ;
// geo
GET_OBJECT(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(geo)),ptr->geo,parse_geo);
// user
GET_OBJECT(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(user)),ptr->user,parse_user);
// retweeted_status
GET_OBJECT(XML,obj,GET_VALUEKEY(WBPARSER_KEY_STATEIDX(retstatus)),ptr->retweeted_status,parse_status);
}
struct t_wbParse_Error* CWBXmlParser::parse_error(wbParserNS::REQOBJ *obj)
{
t_wbParse_Error* ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Error,wbParse_Malloc_Error(1) );
parse_error(obj,ptr);
}
return ptr;
}
void CWBXmlParser::parse_error(wbParserNS::REQOBJ *obj , t_wbParse_Error * ptr)
{
if( !ptr || !obj )
return ;
int len = 0;
const char* txt = NULL;
//
//txt = wbParserNS::GetCHAR_Key_XML_EX("request" , obj , len );
GET_STR_EX(XML,obj,"request",txt,len );
if( len && txt ) {
strncpy( ptr->request ,txt , WBPARSER_USE_LEN(request) );
}
//txt = wbParserNS::GetCHAR_Key_JSON_EX("error_code" , obj, len);
GET_STR_EX(XML,obj,"error_code",txt,len);
if( len && txt ) {
strncpy( ptr->error_code,txt , WBPARSER_USE_LEN(error_code) );
}
//txt = wbParserNS::GetCHAR_Key_JSON_EX("error" , obj, len);
GET_STR_EX(XML,obj,"error",txt,len);
if( len && txt ) {
strncpy( ptr->error,txt,WBPARSER_USE_LEN(error) );
ptr->error_sub_code = atoi(ptr->error);
}
}
/** 解析用户 */
t_wbParse_User *CWBXmlParser::parse_user(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_User* ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_User,wbParse_Malloc_User(1));
parse_user(obj, ptr );
}
return ptr;
}
void CWBXmlParser::parse_user(wbParserNS::REQOBJ *obj , t_wbParse_User * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// screen_name
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(name)),ptr->screen_name,WBPARSER_USE_LEN(screen_name) );
// name
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(name)),ptr->name,WBPARSER_USE_LEN(name) );
// province
GET_LONG_TO_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(province)),ptr->province,WBPARSER_USE_LEN(province) );
// city
GET_LONG_TO_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(city)),ptr->city,WBPARSER_USE_LEN(city) );
// location
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(location)),ptr->location,WBPARSER_USE_LEN(location) );
// description
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(description)),ptr->description,WBPARSER_USE_LEN(description) );
// url
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(url)),ptr->url,WBPARSER_USE_LEN(url) );
// profile_image_url
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(prourl)),ptr->profile_image_url,WBPARSER_USE_LEN(profile_image_url) );
// domain
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(domain)),ptr->domain,WBPARSER_USE_LEN(domain) );
// gender
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(gender)),ptr->gender,WBPARSER_USE_LEN(gender) );
// created_at
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(createdat)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
// followers_count
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(followcount)),ptr->followers_count );
// followers_count
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(frcount)),ptr->friends_count );
// statuses_count
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(stacount)),ptr->statuses_count );
// favourites_count
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(favcount)),ptr->favourites_count );
// allow_all_act_msg
GET_BOOL(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(allowall)),ptr->allow_all_act_msg );
// geo_enabled
GET_BOOL(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(geoenable)),ptr->geo_enabled );
// following
GET_BOOL(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(following)),ptr->following );
// following
GET_BOOL(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(verified)),ptr->verified );
// last status
USE_WEIBOPARSE_OBJ_PTR;
GET_OBJECT(XML,obj,GET_VALUEKEY(WBPARSER_KEY_USERIDX(last_status)),ptr->last_status,parse_status);
}
/** 解析地理位置 */
t_wbParse_Geo *CWBXmlParser::parse_geo(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Geo *ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Geo,wbParse_Malloc_Geo(1));
parse_geo(obj,ptr);
}
return ptr;
}
void CWBXmlParser::parse_geo(wbParserNS::REQOBJ *obj , t_wbParse_Geo * ptr)
{
if( !ptr || !obj )
return ;
//
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_GEO(type)),ptr->type,WBPARSER_USE_LEN(type)) ;
//
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_GEO(coordinates)),ptr->coordinates,WBPARSER_USE_LEN(coordinates)) ;
}
/** 解析评论 */
t_wbParse_Comment *CWBXmlParser::parse_comment(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Comment *ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Comment,wbParse_Malloc_Comment(1));
parse_comment(obj,ptr);
}
return ptr;
}
void CWBXmlParser::parse_comment(wbParserNS::REQOBJ *obj , t_wbParse_Comment * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// text
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(text)),ptr->text,WBPARSER_USE_LEN(text) );
// source
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(source)),ptr->source,WBPARSER_USE_LEN(source) );
// favorited
GET_BOOL(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(favorited)),ptr->favorited );
// created_at
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(createdat)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
//
USE_WEIBOPARSE_OBJ_PTR ;
// user
GET_OBJECT(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(user)),ptr->user,parse_user);
// status
GET_OBJECT(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(status)),ptr->status,parse_status);
// reply_comment
GET_OBJECT(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(rcomment)),ptr->reply_comment,parse_comment);
}
/** 私信 */
t_wbParse_DirectMessage *CWBXmlParser::parse_directmessage(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_DirectMessage* ptr =0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_DirectMessage,wbParse_Malloc_Directmessage(1));
parse_directmessage(obj,ptr);
}
return ptr;
}
void CWBXmlParser::parse_directmessage(wbParserNS::REQOBJ *obj , t_wbParse_DirectMessage * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(id)),ptr->id,WBPARSER_USE_LEN(id) );
// text
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(text)),ptr->text,WBPARSER_USE_LEN(text) );
// created_at
GET_STR(XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMMENTIDX(createdat)),ptr->created_at,WBPARSER_USE_LEN(created_at) );
// sender_id
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(senderid)),ptr->sender_id,WBPARSER_USE_LEN(id) );
// recipient_id
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(recipientid)),ptr->recipient_id,WBPARSER_USE_LEN(id) );
// sender_screen_name
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(sndsname)),ptr->sender_screen_name,WBPARSER_USE_LEN(name) );
//recipient_screen_name
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(rsnsame)),ptr->recipient_screen_name,WBPARSER_USE_LEN(name) );
//
USE_WEIBOPARSE_OBJ_PTR ;
//sender
GET_OBJECT( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(sender)),ptr->sender,parse_user );
//recipient
GET_OBJECT( XML,obj,GET_VALUEKEY(WBPARSER_KEY_DIRMSGIDX(recipient)),ptr->recipient,parse_user );
}
/** 解析未读数 */
t_wbParse_Unread *CWBXmlParser::parse_unread(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Unread *ptr = 0;
if( obj )
{
ptr = WEIBO_PARSER_CAST(t_wbParse_Unread,wbParse_Malloc_Unread(1));
parse_unread(obj ,ptr );
}
return ptr;
}
void CWBXmlParser::parse_unread(wbParserNS::REQOBJ *obj , t_wbParse_Unread * ptr)
{
if( !ptr || !obj )
return ;
// comments
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(comments)),ptr->comments);
// mentions
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(mentions)),ptr->mentions);
// dm
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(dm)),ptr->dm);
// followers
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(followers)),ptr->followers);
GET_LONG(XML,obj,GET_VALUEKEY(WBPARSER_KEY_UREADER(new_status)),ptr->new_status);
}
/** 解析评论计数 */
t_wbParse_CommentCounts *CWBXmlParser::parse_commentcounts(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_CommentCounts *ptr = 0;
if( obj)
{
ptr = WEIBO_PARSER_CAST(t_wbParse_CommentCounts,wbParse_Malloc_Commentcount(1));
parse_commentcounts(obj,ptr);
}
return ptr;
}
void CWBXmlParser::parse_commentcounts(wbParserNS::REQOBJ *obj , t_wbParse_CommentCounts * ptr)
{
if( !ptr || !obj )
return ;
// id
GET_LONG_TO_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMCOUNT(id)),ptr->id,WBPARSER_USE_LEN(id) );
// comments
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMCOUNT(comments)),ptr->comments );
// rt
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_COMCOUNT(rt)),ptr->rt );
}
t_wbParse_LimitStatus *CWBXmlParser::parse_limite_status(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_LimitStatus *ptr = 0;
if( obj)
{
ptr = (t_wbParse_LimitStatus *)wbParse_Malloc_Limits(1);
parse_limite_status(obj , ptr);
}
return ptr;
}
void CWBXmlParser::parse_limite_status(wbParserNS::REQOBJ *obj , t_wbParse_LimitStatus * ptr)
{
if( !ptr || !obj )
return ;
// hourly_limit
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(hourlimit)),ptr->hourly_limit );
// rstimeinseond
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(rstimeinseond)),ptr->reset_time_in_seconds );
// remaining_hits
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(remaining_hits)),ptr->remaining_hits );
// reset_time
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_ACCESS_LMT(reset_time)),ptr->reset_time,WBPARSER_USE_LEN(reset_time) );
}
t_wbParse_Emotion *CWBXmlParser::parse_emotion(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Emotion *ptr = 0;
if( obj )
{
ptr = (t_wbParse_Emotion *)wbParse_Malloc_Emotion(1);
parse_emotion(obj , ptr);
}
return ptr;
}
void CWBXmlParser::parse_emotion(wbParserNS::REQOBJ *obj , t_wbParse_Emotion * ptr)
{
if( !ptr || !obj )
return ;
// phrase
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(phrase)),ptr->phrase,WBPARSER_USE_LEN(phrase) );
// type
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(type)),ptr->type,WBPARSER_USE_LEN(type) );
// url
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(url)),ptr->url,WBPARSER_USE_LEN(url) );
//category
GET_STR( XML,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(category)),ptr->category,WBPARSER_USE_LEN(category) );
// is_hot
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(is_hot)),ptr->is_hot );
// is_common
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(is_common)),ptr->is_common );
// order_number
GET_LONG( XML,obj,GET_VALUEKEY(WBPARSER_KEY_EMOTION(order_number)),ptr->order_number );
}
t_wbParse_Shipshow *CWBXmlParser::parse_shipshow(/*[in]*/wbParserNS::REQOBJ *obj)
{
t_wbParse_Shipshow *ptr = 0;
if( obj )
{
ptr = (t_wbParse_Shipshow *)wbParse_Malloc_Friendship(1);
parse_shipshow(obj , ptr);
}
return ptr;
}
void CWBXmlParser::parse_shipshow(/*[in]*/wbParserNS::REQOBJ *obj,t_wbParse_Shipshow *ptr)
{
//{
// "source":{
// "id":245110499
// ,"screen_name":"245110499"
// ,"following":false
// ,"followed_by":false
// ,"notifications_enabled":false
// }
// ,"target":{
// "id":10503
// ,"screen_name":"10503"
// ,"following":false
// ,"followed_by":false
// ,"notifications_enabled":false
// }
//}
if( !ptr || !obj )
return ;
//
USE_WEIBOPARSE_OBJ_PTR ;
//source
GET_OBJECT( XML,obj,"source",ptr->source,parse_ship_item );
//source
GET_OBJECT( XML,obj,"target",ptr->target,parse_ship_item );
}
t_wbParse_Shipshow::Item* CWBXmlParser::parse_ship_item(wbParserNS::REQOBJ *obj)
{
// "source":{
// "id":245110499
// ,"screen_name":"245110499"
// ,"following":false
// ,"followed_by":false
// ,"notifications_enabled":false
// }
if( !obj )
return 0;
t_wbParse_Shipshow::Item* ptr = (t_wbParse_Shipshow::Item*)malloc(sizeof(t_wbParse_Shipshow::Item));
memset(ptr , 0 , sizeof(t_wbParse_Shipshow::Item));
// id
GET_LONG_TO_STR( XML,obj,"id",ptr->id,WBPARSER_USE_LEN(id) );
// screen_name
GET_STR( XML,obj,"screen_name",ptr->screen_name,WBPARSER_USE_LEN(screen_name) );
// following
GET_LONG( XML,obj,"following",ptr->following);
// following
GET_LONG( XML,obj,"followed_by",ptr->followed_by);
// following
GET_LONG( XML,obj,"notifications_enabled",ptr->notifications_enabled);
return ptr;
}
#endif //#if defined(_USE_XML_PARSER)
extern
void wbParserNS::CheckShortLink(struct t_wbParse_Status *pStatus ,const char* wbParentId , t_wbParse_Media** pMedia , int& size ,int cmd)
{
if( !pStatus || !pMedia )
return ;
const char* szText = pStatus->text;
const char* szEnd = szText + WBPARSER_USE_LEN(text);
const char* start = 0;
const char* end = 0,*shortID = 0;
while( 0 == wb_split_shortlink( szText , szEnd , start , end , shortID ) )
{
t_wbParse_Media* pmtemp = 0;
if( 0 == *pMedia )
{
size = 1;
*pMedia = (t_wbParse_Media*)wbParse_Malloc_Media(1);
pmtemp = *pMedia;
}
else
{// 累积
*pMedia = (t_wbParse_Media*)realloc(*pMedia , sizeof(t_wbParse_Media)*(size+1));
pmtemp = *pMedia + (size++);
memset(pmtemp , 0 , sizeof(t_wbParse_Media));
}
pmtemp->cmd = cmd;
// fill media information
if (wbParentId)
{
strncpy(pmtemp->parentid , wbParentId , WBPARSER_USE_LEN(id) );
}
strncpy(pmtemp->id ,pStatus->id , WBPARSER_USE_LEN(id) );
strncpy(pmtemp->mitem.id , shortID , end - shortID );
// 下一个
szText = end;
}
if( pStatus ->retweeted_status )
{
CheckShortLink(pStatus ->retweeted_status , pStatus->id , pMedia , size,cmd);
}
}
extern
void wbParserNS::MMIdCompare(struct t_wbParser_MMId* pMMId ,t_wbParser_MMId::eType type ,const char* id , const char* time)
{
long long ll = 0;
#if defined(WIN32)
ll = _atoi64(id);
#else
#error("not support")
#endif
struct t_wbParser_MMId::IdValue* idv = &pMMId->_idVal[type];
if( idv->maxId < ll )
idv->maxId = ll;
if( idv->minId > ll || (idv->minId == llMAX))
idv->minId = ll;
}
| [
"[email protected]@6d9c6d06-b0b6-dbdc-3531-a27e122abd9f"
] | [
[
[
1,
1650
]
]
] |
04b7554bef07258e867c26000629f6056a10e9ae | a7a890e753c6f69e8067d16a8cd94ce8327f80b7 | /jclient/network.cpp | 41212987fd716dffe4e6cf75d4d74dece0987bc9 | [] | no_license | jbreslin33/breslinservergame | 684ca8b97f36e265f30ae65e1a65435b2e7a3d8b | 292285f002661c3d9483fb080845564145d47999 | refs/heads/master | 2021-01-21T13:11:50.223394 | 2011-03-14T11:33:30 | 2011-03-14T11:33:30 | 37,391,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,811 | cpp | /******************************************/
/* MMOG programmer's guide */
/* Tutorial game client */
/* Programming: */
/* Teijo Hakala */
/******************************************/
//#include "Tutorial4.h"
char serverIP[32] = "127.0.0.1";
//char serverIP[32] = "192.168.1.104";
#include "client.h"
#include "../dreamsock/DreamClient.h"
#include "../dreamsock/DreamSock.h"
#include "network.h"
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::StartConnection()
{
// LogString("StartConnection");
//gameIndex = ind;
int ret = networkClient->Initialise("", serverIP, 30004);
if(ret == DREAMSOCK_CLIENT_ERROR)
{
char text[64];
sprintf(text, "Could not open client socket");
//MessageBox(NULL, text, "Error", MB_OK);
}
Connect();
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::ReadPackets(void)
{
char data[1400];
struct sockaddr address;
clientData *clList;
int type;
int ind;
int local;
int ret;
char name[50];
DreamMessage mes;
mes.Init(data, sizeof(data));
while(ret = networkClient->GetPacket(mes.data, &address))
{
mes.SetSize(ret);
mes.BeginReading();
type = mes.ReadByte();
switch(type)
{
case DREAMSOCK_MES_ADDCLIENT:
local = mes.ReadByte();
ind = mes.ReadByte();
strcpy(name, mes.ReadString());
AddClient(local, ind, name);
break;
case DREAMSOCK_MES_REMOVECLIENT:
ind = mes.ReadByte();
LogString("Got removeclient %d message", ind);
RemoveClient(ind);
break;
case USER_MES_FRAME:
// Skip sequences
mes.ReadShort();
mes.ReadShort();
for(clList = clientList; clList != NULL; clList = clList->next)
{
// LogString("Reading DELTAFRAME for client %d", clList->index);
ReadDeltaMoveCommand(&mes, clList);
}
break;
case USER_MES_NONDELTAFRAME:
// Skip sequences
mes.ReadShort();
mes.ReadShort();
clList = clientList;
for(clList = clientList; clList != NULL; clList = clList->next)
{
LogString("Reading NONDELTAFRAME for client %d", clList->index);
ReadMoveCommand(&mes, clList);
}
break;
case USER_MES_SERVEREXIT:
//MessageBox(NULL, "Server disconnected", "Info", MB_OK);
Disconnect();
break;
}
}
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::AddClient(int local, int ind, char *name)
{
// First get a pointer to the beginning of client list
clientData *list = clientList;
clientData *prev;
LogString("App: Client: Adding client with index %d", ind);
// No clients yet, adding the first one
if(clientList == NULL)
{
LogString("App: Client: Adding first client");
clientList = (clientData *) calloc(1, sizeof(clientData));
if(local)
{
LogString("App: Client: This one is local");
localClient = clientList;
}
clientList->index = ind;
strcpy(clientList->nickname, name);
if(clients % 2 == 0)
createPlayer(ind);
else
createPlayer(ind);
clientList->next = NULL;
}
else
{
LogString("App: Client: Adding another client");
prev = list;
list = clientList->next;
while(list != NULL)
{
prev = list;
list = list->next;
}
list = (clientData *) calloc(1, sizeof(clientData));
if(local)
{
LogString("App: Client: This one is local");
localClient = list;
}
list->index = ind;
strcpy(list->nickname, name);
clientList->next = NULL;
list->next = NULL;
prev->next = list;
if(clients % 2 == 0)
createPlayer(ind);
else
createPlayer(ind);
}
clients++;
// If we just joined the game, request a non-delta compressed frame
if(local)
SendRequestNonDeltaFrame();
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::RemoveClient(int ind)
{
clientData *list = clientList;
clientData *prev = NULL;
clientData *next = NULL;
// Look for correct client and update list
for( ; list != NULL; list = list->next)
{
if(list->index == ind)
{
if(prev != NULL)
{
prev->next = list->next;
}
break;
}
prev = list;
}
// First entry
if(list == clientList)
{
if(list)
{
next = list->next;
free(list);
}
list = NULL;
clientList = next;
}
// Other
else
{
if(list)
{
next = list->next;
free(list);
}
list = next;
}
clients--;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::RemoveClients(void)
{
clientData *list = clientList;
clientData *next;
while(list != NULL)
{
if(list)
{
next = list->next;
free(list);
}
list = next;
}
clientList = NULL;
clients = 0;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::SendCommand(void)
{
if(networkClient->GetConnectionState() != DREAMSOCK_CONNECTED)
return;
DreamMessage message;
char data[1400];
int i = networkClient->GetOutgoingSequence() & (COMMAND_HISTORY_SIZE-1);
message.Init(data, sizeof(data));
message.WriteByte(USER_MES_FRAME); // type
message.AddSequences(networkClient); // sequences
// Build delta-compressed move command
BuildDeltaMoveCommand(&message, &inputClient);
// Send the packet
networkClient->SendPacket(&message);
// Store the command to the input client's history
memcpy(&inputClient.frame[i], &inputClient.command, sizeof(command_t));
clientData *clList = clientList;
// Store the commands to the clients' history
for( ; clList != NULL; clList = clList->next)
{
memcpy(&clList->frame[i], &clList->command, sizeof(command_t));
}
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::SendRequestNonDeltaFrame(void)
{
char data[1400];
DreamMessage message;
message.Init(data, sizeof(data));
message.WriteByte(USER_MES_NONDELTAFRAME);
message.AddSequences(networkClient);
networkClient->SendPacket(&message);
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::Connect(void)
{
if(init)
{
LogString("ArmyWar already initialised");
return;
}
LogString("CArmyWar::Connect");
init = true;
networkClient->SendConnect("myname");
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::Disconnect(void)
{
if(!init)
return;
LogString("CArmyWar::Disconnect");
init = false;
localClient = NULL;
memset(&inputClient, 0, sizeof(clientData));
networkClient->SendDisconnect();
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::ReadMoveCommand(DreamMessage *mes, clientData *client)
{
// Key
client->serverFrame.key = mes->ReadByte();
// Heading
//client->serverFrame.heading = mes->ReadShort();
// Origin
client->serverFrame.origin.x = mes->ReadFloat();
client->serverFrame.origin.y = mes->ReadFloat();
client->serverFrame.vel.x = mes->ReadFloat();
client->serverFrame.vel.y = mes->ReadFloat();
// Read time to run command
client->serverFrame.msec = mes->ReadByte();
memcpy(&client->command, &client->serverFrame, sizeof(command_t));
// Fill the history array with the position we got
for(int f = 0; f < COMMAND_HISTORY_SIZE; f++)
{
client->frame[f].predictedOrigin.x = client->command.origin.x;
client->frame[f].predictedOrigin.y = client->command.origin.y;
}
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::ReadDeltaMoveCommand(DreamMessage *mes, clientData *client)
{
int processedFrame;
int flags = 0;
// Flags
flags = mes->ReadByte();
// Key
if(flags & CMD_KEY)
{
client->serverFrame.key = mes->ReadByte();
client->command.key = client->serverFrame.key;
LogString("Client %d: Read key %d", client->index, client->command.key);
}
if(flags & CMD_ORIGIN)
{
processedFrame = mes->ReadByte();
}
// Origin
if(flags & CMD_ORIGIN)
{
client->serverFrame.origin.x = mes->ReadFloat();
client->serverFrame.origin.y = mes->ReadFloat();
client->serverFrame.vel.x = mes->ReadFloat();
client->serverFrame.vel.y = mes->ReadFloat();
if(client == localClient)
{
CheckPredictionError(processedFrame);
}
else
{
client->command.origin.x = client->serverFrame.origin.x;
client->command.origin.y = client->serverFrame.origin.y;
client->command.vel.x = client->serverFrame.vel.x;
client->command.vel.y = client->serverFrame.vel.y;
}
}
// Read time to run command
client->command.msec = mes->ReadByte();
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::BuildDeltaMoveCommand(DreamMessage *mes, clientData *theClient)
{
int flags = 0;
int last = (networkClient->GetOutgoingSequence() - 1) & (COMMAND_HISTORY_SIZE-1);
// Check what needs to be updated
if(theClient->frame[last].key != theClient->command.key)
flags |= CMD_KEY;
// Add to the message
// Flags
mes->WriteByte(flags);
// Key
if(flags & CMD_KEY)
{
mes->WriteByte(theClient->command.key);
}
mes->WriteByte(theClient->command.msec);
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWar::RunNetwork(int msec)
{
static int time = 0;
time += msec;
// Framerate is too high
if(time < (1000 / 60))
return;
frametime = time / 1000.0f;
time = 0;
// Read packets from server, and send new commands
ReadPackets();
SendCommand();
int ack = networkClient->GetIncomingAcknowledged();
int current = networkClient->GetOutgoingSequence();
// Check that we haven't gone too far
if(current - ack > COMMAND_HISTORY_SIZE)
return;
// Predict the frames that we are waiting from the server
for(int a = ack + 1; a < current; a++)
{
int prevframe = (a-1) & (COMMAND_HISTORY_SIZE-1);
int frame = a & (COMMAND_HISTORY_SIZE-1);
PredictMovement(prevframe, frame);
}
MoveObjects();
}
| [
"jbreslin33@localhost"
] | [
[
[
1,
520
]
]
] |
5c63dc1611f11b9c2a8e2b58d4208e1a442addc1 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/multi_index/test/test_copy_assignment.cpp | cd64a899889bfb82925d732f25e855e8dad28c19 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,764 | cpp | /* Boost.MultiIndex test for copying and assignment.
*
* Copyright 2003-2006 Joaquín M López Muñoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/multi_index for library home page.
*/
#include "test_copy_assignment.hpp"
#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <algorithm>
#include <list>
#include <numeric>
#include <vector>
#include "pre_multi_index.hpp"
#include "employee.hpp"
#include <boost/test/test_tools.hpp>
using namespace boost::multi_index;
#if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
/* The "ISO C++ Template Parser" option makes CW8.3 incorrectly fail at
* expressions of the form sizeof(x) where x is an array local to a
* template function.
*/
#pragma parse_func_templ off
#endif
template<typename Sequence>
static void test_assign(BOOST_EXPLICIT_TEMPLATE_TYPE(Sequence))
{
Sequence s;
int a[]={0,1,2,3,4,5};
std::size_t sa=sizeof(a)/sizeof(a[0]);
s.assign(&a[0],&a[sa]);
BOOST_CHECK(s.size()==sa&&std::equal(s.begin(),s.end(),&a[0]));
s.assign(&a[0],&a[sa]);
BOOST_CHECK(s.size()==sa&&std::equal(s.begin(),s.end(),&a[0]));
s.assign((std::size_t)18,37);
BOOST_CHECK(s.size()==18&&std::accumulate(s.begin(),s.end(),0)==666);
s.assign((std::size_t)12,167);
BOOST_CHECK(s.size()==12&&std::accumulate(s.begin(),s.end(),0)==2004);
}
#if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
#pragma parse_func_templ reset
#endif
void test_copy_assignment()
{
employee_set es;
employee_set es2(es);
employee_set::allocator_type al=es.get_allocator();
al=get<1>(es).get_allocator();
al=get<2>(es).get_allocator();
al=get<3>(es).get_allocator();
al=get<4>(es).get_allocator();
al=get<5>(es).get_allocator();
BOOST_CHECK(es2.empty());
es2.insert(employee(0,"Joe",31,1123));
es2.insert(employee(1,"Robert",27,5601));
es2.insert(employee(2,"John",40,7889));
es2.insert(employee(2,"Aristotle",2388,3357)); /* clash */
es2.insert(employee(3,"Albert",20,9012));
es2.insert(employee(4,"John",57,1002));
es2.insert(employee(0,"Andrew",60,2302)); /* clash */
employee_set es3(es2);
BOOST_CHECK(es2==es3);
BOOST_CHECK(get<2>(es2)==get<2>(es3));
BOOST_CHECK(get<3>(es2)==get<3>(es3));
BOOST_CHECK(get<5>(es2)==get<5>(es3));
employee_set es4;
employee_set_by_name& i1=get<name>(es4);
i1=get<1>(es2);
BOOST_CHECK(es4==es2);
employee_set es5;
employee_set_by_age& i2=get<age>(es5);
i2=get<2>(es2);
BOOST_CHECK(i2==get<2>(es2));
employee_set es6;
employee_set_as_inserted& i3=get<as_inserted>(es6);
i3=get<3>(es2);
BOOST_CHECK(i3==get<3>(es2));
employee_set es7;
employee_set_randomly& i5=get<randomly>(es7);
i5=get<5>(es2);
BOOST_CHECK(i5==get<5>(es2));
std::list<employee> l;
l.push_back(employee(3,"Anna",31,5388));
l.push_back(employee(1,"Rachel",27,9012));
l.push_back(employee(2,"Agatha",40,1520));
#if BOOST_WORKAROUND(BOOST_MSVC,<1300)
employee_set es8;
es8.insert(l.begin(),l.end());
#else
employee_set es8(l.begin(),l.end());
#endif
l.sort();
BOOST_CHECK(es8.size()==l.size()&&
std::equal(es8.begin(),es8.end(),l.begin()));
/* MSVC++ 6.0 chokes on test_assign without this explicit instantiation */
multi_index_container<int,indexed_by<sequenced<> > > s1;
test_assign<multi_index_container<int,indexed_by<sequenced<> > > >();
multi_index_container<int,indexed_by<random_access<> > > s2;
test_assign<multi_index_container<int,indexed_by<random_access<> > > >();
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
136
]
]
] |
7c8a390083b438d7fb033a5c9278ae9f40338977 | 028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32 | /src/sound/ymz280b.cpp | c250bae0215b00c6160f8d20b14eb6ade3d4a2d3 | [] | no_license | neonichu/iMame4All-for-iPad | 72f56710d2ed7458594838a5152e50c72c2fb67f | 4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611 | refs/heads/master | 2020-04-21T07:26:37.595653 | 2011-11-26T12:21:56 | 2011-11-26T12:21:56 | 2,855,022 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,631 | cpp | /**********************************************************************************************
*
* Yamaha YMZ280B driver
* by Aaron Giles
*
**********************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "driver.h"
#include "adpcm.h"
#include "osinline.h"
#define MAX_SAMPLE_CHUNK 10000
#define FRAC_BITS 14
#define FRAC_ONE (1 << FRAC_BITS)
#define FRAC_MASK (FRAC_ONE - 1)
/* struct describing a single playing ADPCM voice */
struct YMZ280BVoice
{
UINT8 playing; /* 1 if we are actively playing */
UINT8 keyon; /* 1 if the key is on */
UINT8 looping; /* 1 if looping is enabled */
UINT8 mode; /* current playback mode */
UINT16 fnum; /* frequency */
UINT8 level; /* output level */
UINT8 pan; /* panning */
UINT32 start; /* start address, in nibbles */
UINT32 stop; /* stop address, in nibbles */
UINT32 loop_start; /* loop start address, in nibbles */
UINT32 loop_end; /* loop end address, in nibbles */
UINT32 position; /* current position, in nibbles */
INT32 signal; /* current ADPCM signal */
INT32 step; /* current ADPCM step */
INT32 loop_signal; /* signal at loop start */
INT32 loop_step; /* step at loop start */
UINT32 loop_count; /* number of loops so far */
INT32 output_left; /* output volume (left) */
INT32 output_right; /* output volume (right) */
INT32 output_step; /* step value for frequency conversion */
INT32 output_pos; /* current fractional position */
INT16 last_sample; /* last sample output */
INT16 curr_sample; /* current sample target */
};
struct YMZ280BChip
{
int stream; /* which stream are we using */
UINT8 *region_base; /* pointer to the base of the region */
UINT8 current_register; /* currently accessible register */
UINT8 status_register; /* current status register */
UINT8 irq_state; /* current IRQ state */
UINT8 irq_mask; /* current IRQ mask */
UINT8 irq_enable; /* current IRQ enable */
UINT8 keyon_enable; /* key on enable */
float master_clock; /* master clock frequency */
void (*irq_callback)(int); /* IRQ callback */
struct YMZ280BVoice voice[8]; /* the 8 voices */
};
static struct YMZ280BChip ymz280b[MAX_YMZ280B];
static INT32 *accumulator;
static INT16 *scratch;
/* step size index shift table */
static int index_scale[8] = { 0x0e6, 0x0e6, 0x0e6, 0x0e6, 0x133, 0x199, 0x200, 0x266 };
/* lookup table for the precomputed difference */
static int diff_lookup[16];
INLINE void update_irq_state(struct YMZ280BChip *chip)
{
int irq_bits = chip->status_register & chip->irq_mask;
/* always off if the enable is off */
if (!chip->irq_enable)
irq_bits = 0;
/* update the state if changed */
if (irq_bits && !chip->irq_state)
{
chip->irq_state = 1;
if (chip->irq_callback)
(*chip->irq_callback)(1);
}
else if (!irq_bits && chip->irq_state)
{
chip->irq_state = 0;
if (chip->irq_callback)
(*chip->irq_callback)(0);
}
}
INLINE void update_step(struct YMZ280BChip *chip, struct YMZ280BVoice *voice)
{
float frequency;
/* handle the sound-off case */
if (Machine->sample_rate == 0)
{
voice->output_step = 0;
return;
}
/* compute the frequency */
if (voice->mode == 1)
frequency = chip->master_clock * (float)((voice->fnum & 0x0ff) + 1) * (1.0 / 256.0);
else
frequency = chip->master_clock * (float)((voice->fnum & 0x1ff) + 1) * (1.0 / 256.0);
voice->output_step = (UINT32)(frequency * (float)FRAC_ONE / (float)Machine->sample_rate);
}
INLINE void update_volumes(struct YMZ280BVoice *voice)
{
if (voice->pan == 8)
{
voice->output_left = voice->level;
voice->output_right = voice->level;
}
else if (voice->pan < 8)
{
voice->output_left = voice->level;
voice->output_right = voice->level * voice->pan / 8;
}
else
{
voice->output_left = voice->level * (15 - voice->pan) / 8;
voice->output_right = voice->level;
}
}
/**********************************************************************************************
compute_tables -- compute the difference tables
***********************************************************************************************/
static void compute_tables(void)
{
int nib;
/* loop over all nibbles and compute the difference */
for (nib = 0; nib < 16; nib++)
{
int value = (nib & 0x07) * 2 + 1;
diff_lookup[nib] = (nib & 0x08) ? -value : value;
}
}
/**********************************************************************************************
generate_adpcm -- general ADPCM decoding routine
***********************************************************************************************/
static int generate_adpcm(struct YMZ280BVoice *voice, UINT8 *base, INT16 *buffer, int samples)
{
int position = voice->position;
int signal = voice->signal;
int step = voice->step;
int val;
/* two cases: first cases is non-looping */
if (!voice->looping)
{
/* loop while we still have samples to generate */
while (samples)
{
/* compute the new amplitude and update the current step */
val = base[position / 2] >> ((~position & 1) << 2);
signal += (step * diff_lookup[val & 15]) / 8;
/* clamp to the maximum */
#ifndef clip_short
if (signal > 32767)
signal = 32767;
else if (signal < -32768)
signal = -32768;
#else
clip_short(signal);
#endif
/* adjust the step size and clamp */
step = (step * index_scale[val & 7]) >> 8;
if (step > 0x6000)
step = 0x6000;
else if (step < 0x7f)
step = 0x7f;
/* output to the buffer, scaling by the volume */
*buffer++ = signal;
samples--;
/* next! */
position++;
if (position >= voice->stop)
break;
}
}
/* second case: looping */
else
{
/* loop while we still have samples to generate */
while (samples)
{
/* compute the new amplitude and update the current step */
val = base[position / 2] >> ((~position & 1) << 2);
signal += (step * diff_lookup[val & 15]) / 8;
/* clamp to the maximum */
#ifndef clip_short
if (signal > 32767)
signal = 32767;
else if (signal < -32768)
signal = -32768;
#else
clip_short(signal);
#endif
/* adjust the step size and clamp */
step = (step * index_scale[val & 7]) >> 8;
if (step > 0x6000)
step = 0x6000;
else if (step < 0x7f)
step = 0x7f;
/* output to the buffer, scaling by the volume */
*buffer++ = signal;
samples--;
/* next! */
position++;
if (position == voice->loop_start && voice->loop_count == 0)
{
voice->loop_signal = signal;
voice->loop_step = step;
}
if (position >= voice->loop_end)
{
if (voice->keyon)
{
position = voice->loop_start;
signal = voice->loop_signal;
step = voice->loop_step;
voice->loop_count++;
}
}
if (position >= voice->stop)
break;
}
}
/* update the parameters */
voice->position = position;
voice->signal = signal;
voice->step = step;
return samples;
}
/**********************************************************************************************
generate_pcm8 -- general 8-bit PCM decoding routine
***********************************************************************************************/
static int generate_pcm8(struct YMZ280BVoice *voice, UINT8 *base, INT16 *buffer, int samples)
{
int position = voice->position;
int val;
/* two cases: first cases is non-looping */
if (!voice->looping)
{
/* loop while we still have samples to generate */
while (samples)
{
/* fetch the current value */
val = base[position / 2];
/* output to the buffer, scaling by the volume */
*buffer++ = (INT8)val * 256;
samples--;
/* next! */
position += 2;
if (position >= voice->stop)
break;
}
}
/* second case: looping */
else
{
/* loop while we still have samples to generate */
while (samples)
{
/* fetch the current value */
val = base[position / 2];
/* output to the buffer, scaling by the volume */
*buffer++ = (INT8)val * 256;
samples--;
/* next! */
position += 2;
if (position >= voice->loop_end)
{
if (voice->keyon)
position = voice->loop_start;
}
if (position >= voice->stop)
break;
}
}
/* update the parameters */
voice->position = position;
return samples;
}
/**********************************************************************************************
generate_pcm16 -- general 16-bit PCM decoding routine
***********************************************************************************************/
static int generate_pcm16(struct YMZ280BVoice *voice, UINT8 *base, INT16 *buffer, int samples)
{
int position = voice->position;
int val;
/* two cases: first cases is non-looping */
if (!voice->looping)
{
/* loop while we still have samples to generate */
while (samples)
{
/* fetch the current value */
val = (INT16)((base[position / 2 + 1] << 8) + base[position / 2]);
/* output to the buffer, scaling by the volume */
*buffer++ = val;
samples--;
/* next! */
position += 4;
if (position >= voice->stop)
break;
}
}
/* second case: looping */
else
{
/* loop while we still have samples to generate */
while (samples)
{
/* fetch the current value */
val = (INT16)((base[position / 2 + 1] << 8) + base[position / 2]);
/* output to the buffer, scaling by the volume */
*buffer++ = val;
samples--;
/* next! */
position += 4;
if (position >= voice->loop_end)
{
if (voice->keyon)
position = voice->loop_start;
}
if (position >= voice->stop)
break;
}
}
/* update the parameters */
voice->position = position;
return samples;
}
/**********************************************************************************************
ymz280b_update -- update the sound chip so that it is in sync with CPU execution
***********************************************************************************************/
static void ymz280b_update(int num, INT16 **buffer, int length)
{
struct YMZ280BChip *chip = &ymz280b[num];
INT32 *lacc = accumulator;
INT32 *racc = accumulator + length;
int v;
/* clear out the accumulator */
memset(accumulator, 0, 2 * length * sizeof(accumulator[0]));
/* loop over voices */
for (v = 0; v < 8; v++)
{
struct YMZ280BVoice *voice = &chip->voice[v];
INT16 prev = voice->last_sample;
INT16 curr = voice->curr_sample;
INT16 *curr_data = scratch;
INT32 *ldest = lacc;
INT32 *rdest = racc;
UINT32 new_samples, samples_left;
UINT32 final_pos;
int remaining = length;
int lvol = voice->output_left;
int rvol = voice->output_right;
/* quick out if we're not playing and we're at 0 */
if (!voice->playing && curr == 0)
continue;
/* finish off the current sample */
if (voice->output_pos > 0)
{
/* interpolate */
while (remaining > 0 && voice->output_pos < FRAC_ONE)
{
int interp_sample = (((INT32)prev * (FRAC_ONE - voice->output_pos)) + ((INT32)curr * voice->output_pos)) >> FRAC_BITS;
*ldest++ += interp_sample * lvol;
*rdest++ += interp_sample * rvol;
voice->output_pos += voice->output_step;
remaining--;
}
/* if we're over, continue; otherwise, we're done */
if (voice->output_pos >= FRAC_ONE)
voice->output_pos -= FRAC_ONE;
else
continue;
}
/* compute how many new samples we need */
final_pos = voice->output_pos + remaining * voice->output_step;
new_samples = (final_pos + FRAC_ONE - 1) >> FRAC_BITS;
if (new_samples > MAX_SAMPLE_CHUNK)
new_samples = MAX_SAMPLE_CHUNK;
samples_left = new_samples;
/* generate them into our buffer */
if (voice->playing)
{
switch (voice->mode)
{
case 1: samples_left = generate_adpcm(voice, chip->region_base, scratch, new_samples); break;
case 2: samples_left = generate_pcm8(voice, chip->region_base, scratch, new_samples); break;
case 3: samples_left = generate_pcm16(voice, chip->region_base, scratch, new_samples); break;
default:
case 0: samples_left = 0; memset(scratch, 0, new_samples * sizeof(scratch[0])); break;
}
}
/* if there are leftovers, ramp back to 0 */
if (samples_left)
{
int base = new_samples - samples_left;
int i, t = (base == 0) ? curr : scratch[base - 1];
for (i = 0; i < samples_left; i++)
{
if (t < 0) t = -((-t * 15) >> 4);
else if (t > 0) t = (t * 15) >> 4;
scratch[base + i] = t;
}
/* if we hit the end and IRQs are enabled, signal it */
if (base != 0)
{
voice->playing = 0;
chip->status_register |= 1 << v;
update_irq_state(chip);
}
}
/* advance forward one sample */
prev = curr;
curr = *curr_data++;
/* then sample-rate convert with linear interpolation */
while (remaining > 0)
{
/* interpolate */
while (remaining > 0 && voice->output_pos < FRAC_ONE)
{
int interp_sample = (((INT32)prev * (FRAC_ONE - voice->output_pos)) + ((INT32)curr * voice->output_pos)) >> FRAC_BITS;
*ldest++ += interp_sample * lvol;
*rdest++ += interp_sample * rvol;
voice->output_pos += voice->output_step;
remaining--;
}
/* if we're over, grab the next samples */
if (voice->output_pos >= FRAC_ONE)
{
voice->output_pos -= FRAC_ONE;
prev = curr;
curr = *curr_data++;
}
}
/* remember the last samples */
voice->last_sample = prev;
voice->curr_sample = curr;
}
/* mix and clip the result */
for (v = 0; v < length; v++)
{
int lsamp = lacc[v] / 256;
int rsamp = racc[v] / 256;
#ifndef clip_short
if (lsamp < -32768) lsamp = -32768;
else if (lsamp > 32767) lsamp = 32767;
if (rsamp < -32768) rsamp = -32768;
else if (rsamp > 32767) rsamp = 32767;
#else
clip_short(lsamp);
clip_short(rsamp);
#endif
buffer[0][v] = lsamp;
buffer[1][v] = rsamp;
}
}
/**********************************************************************************************
YMZ280B_sh_start -- start emulation of the YMZ280B
***********************************************************************************************/
int YMZ280B_sh_start(const struct MachineSound *msound)
{
const struct YMZ280Binterface *intf = (const struct YMZ280Binterface *)msound->sound_interface;
char stream_name[2][40];
const char *stream_name_ptrs[2];
int vol[2];
int i;
/* compute ADPCM tables */
compute_tables();
/* initialize the voices */
memset(&ymz280b, 0, sizeof(ymz280b));
for (i = 0; i < intf->num; i++)
{
/* generate the name and create the stream */
sprintf(stream_name[0], "%s #%d (Left)", sound_name(msound), i);
sprintf(stream_name[1], "%s #%d (Right)", sound_name(msound), i);
stream_name_ptrs[0] = stream_name[0];
stream_name_ptrs[1] = stream_name[1];
/* set the volumes */
vol[0] = MIXER(intf->mixing_level[i], MIXER_PAN_LEFT);
vol[1] = MIXER(intf->mixing_level[i], MIXER_PAN_RIGHT);
/* create the stream */
ymz280b[i].stream = stream_init_multi(2, stream_name_ptrs, vol, Machine->sample_rate, i, ymz280b_update);
if (ymz280b[i].stream == -1)
return 1;
/* initialize the rest of the structure */
ymz280b[i].master_clock = (float)intf->baseclock[i] / 384.0;
ymz280b[i].region_base = memory_region(intf->region[i]);
ymz280b[i].irq_callback = intf->irq_callback[i];
}
/* allocate memory */
accumulator = (INT32*)malloc(sizeof(accumulator[0]) * 2 * MAX_SAMPLE_CHUNK);
scratch = (INT16*)malloc(sizeof(scratch[0]) * MAX_SAMPLE_CHUNK);
if (!accumulator || !scratch)
return 1;
/* success */
return 0;
}
/**********************************************************************************************
YMZ280B_sh_stop -- stop emulation of the YMZ280B
***********************************************************************************************/
void YMZ280B_sh_stop(void)
{
/* free memory */
if (accumulator)
free(accumulator);
accumulator = NULL;
if (scratch)
free(scratch);
scratch = NULL;
}
/**********************************************************************************************
write_to_register -- handle a write to the current register
***********************************************************************************************/
static void write_to_register(struct YMZ280BChip *chip, int data)
{
struct YMZ280BVoice *voice;
int i;
/* force an update */
#ifndef MAME_FASTSOUND
stream_update(chip->stream, 0);
#else
{
extern int fast_sound;
if (!fast_sound) stream_update(chip->stream, 0);
}
#endif
/* lower registers follow a pattern */
if (chip->current_register < 0x80)
{
voice = &chip->voice[(chip->current_register >> 2) & 7];
switch (chip->current_register & 0xe3)
{
case 0x00: /* pitch low 8 bits */
voice->fnum = (voice->fnum & 0x100) | (data & 0xff);
update_step(chip, voice);
break;
case 0x01: /* pitch upper 1 bit, loop, key on, mode */
voice->fnum = (voice->fnum & 0xff) | ((data & 0x01) << 8);
voice->looping = (data & 0x10) >> 4;
voice->mode = (data & 0x60) >> 5;
if (!voice->keyon && (data & 0x80) && chip->keyon_enable)
{
voice->playing = 1;
voice->position = voice->start;
voice->signal = voice->loop_signal = 0;
voice->step = voice->loop_step = 0x7f;
voice->loop_count = 0;
}
if (voice->keyon && !(data & 0x80) && !voice->looping)
voice->playing = 0;
voice->keyon = (data & 0x80) >> 7;
update_step(chip, voice);
break;
case 0x02: /* total level */
voice->level = data;
update_volumes(voice);
break;
case 0x03: /* pan */
voice->pan = data & 0x0f;
update_volumes(voice);
break;
case 0x20: /* start address high */
voice->start = (voice->start & (0x00ffff << 1)) | (data << 17);
break;
case 0x21: /* loop start address high */
voice->loop_start = (voice->loop_start & (0x00ffff << 1)) | (data << 17);
break;
case 0x22: /* loop end address high */
voice->loop_end = (voice->loop_end & (0x00ffff << 1)) | (data << 17);
break;
case 0x23: /* stop address high */
voice->stop = (voice->stop & (0x00ffff << 1)) | (data << 17);
break;
case 0x40: /* start address middle */
voice->start = (voice->start & (0xff00ff << 1)) | (data << 9);
break;
case 0x41: /* loop start address middle */
voice->loop_start = (voice->loop_start & (0xff00ff << 1)) | (data << 9);
break;
case 0x42: /* loop end address middle */
voice->loop_end = (voice->loop_end & (0xff00ff << 1)) | (data << 9);
break;
case 0x43: /* stop address middle */
voice->stop = (voice->stop & (0xff00ff << 1)) | (data << 9);
break;
case 0x60: /* start address low */
voice->start = (voice->start & (0xffff00 << 1)) | (data << 1);
break;
case 0x61: /* loop start address low */
voice->loop_start = (voice->loop_start & (0xffff00 << 1)) | (data << 1);
break;
case 0x62: /* loop end address low */
voice->loop_end = (voice->loop_end & (0xffff00 << 1)) | (data << 1);
break;
case 0x63: /* stop address low */
voice->stop = (voice->stop & (0xffff00 << 1)) | (data << 1);
break;
default:
logerror("YMZ280B: unknown register write %02X = %02X\n", chip->current_register, data);
break;
}
}
/* upper registers are special */
else
{
switch (chip->current_register)
{
case 0xfe: /* IRQ mask */
chip->irq_mask = data;
update_irq_state(chip);
break;
case 0xff: /* IRQ enable, test, etc */
chip->irq_enable = (data & 0x10) >> 4;
update_irq_state(chip);
chip->keyon_enable = (data & 0x80) >> 7;
if (!chip->keyon_enable)
for (i = 0; i < 8; i++)
chip->voice[i].playing = 0;
break;
default:
logerror("YMZ280B: unknown register write %02X = %02X\n", chip->current_register, data);
break;
}
}
}
/**********************************************************************************************
compute_status -- determine the status bits
***********************************************************************************************/
static int compute_status(struct YMZ280BChip *chip)
{
UINT8 result = chip->status_register;
/* force an update */
#ifndef MAME_FASTSOUND
stream_update(chip->stream, 0);
#else
{
extern int fast_sound;
if (!fast_sound) stream_update(chip->stream, 0);
}
#endif
/* clear the IRQ state */
chip->status_register = 0;
update_irq_state(chip);
return result;
}
/**********************************************************************************************
YMZ280B_status_0_r/YMZ280B_status_1_r -- handle a read from the status register
***********************************************************************************************/
READ_HANDLER( YMZ280B_status_0_r )
{
return compute_status(&ymz280b[0]);
}
READ_HANDLER( YMZ280B_status_1_r )
{
return compute_status(&ymz280b[1]);
}
/**********************************************************************************************
YMZ280B_register_0_w/YMZ280B_register_1_w -- handle a write to the register select
***********************************************************************************************/
WRITE_HANDLER( YMZ280B_register_0_w )
{
ymz280b[0].current_register = data;
}
WRITE_HANDLER( YMZ280B_register_1_w )
{
ymz280b[1].current_register = data;
}
/**********************************************************************************************
YMZ280B_data_0_w/YMZ280B_data_1_w -- handle a write to the current register
***********************************************************************************************/
WRITE_HANDLER( YMZ280B_data_0_w )
{
write_to_register(&ymz280b[0], data);
}
WRITE_HANDLER( YMZ280B_data_1_w )
{
write_to_register(&ymz280b[1], data);
}
| [
"[email protected]"
] | [
[
[
1,
854
]
]
] |
46d51e9495c04c974ea0bef4623617ff7aaa5a4c | 23c0843109bcc469d7eaf369809a35e643491500 | /Util/File.h | b67232ea10a488d5697e75fa54115ed842aee098 | [] | no_license | takano32/d4r | eb2ab48b324c02634a25fc943e7a805fea8b93a9 | 0629af9d14035b2b768d21982789fc53747a1cdb | refs/heads/master | 2021-01-19T00:46:58.672055 | 2009-01-07T01:28:38 | 2009-01-07T01:28:38 | 102,349 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | h |
#pragma once
#include <windows.h>
namespace base{
class File{
private:
HANDLE _hFile;
LPVOID _pMemory;
public:
File();
~File();
DWORD GetSize();
LPVOID GetMemory();
BOOL Open( LPCTSTR lpFileName );
BOOL Read();
BOOL Close();
BOOL IsOpen();
};
} | [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
fed7843184a17fa4a2c25ac0d56aca85529a5f10 | 823e34ee3931091af33fbac28b5c5683a39278e4 | /WebBrowser/WebBrowserDoc.h | 69e083545811ef9556eae3d9ec05ec17ab0743e4 | [] | no_license | tangooricha/tangoorichas-design-for-graduation | aefdd0fdf0e8786308c22311f2598ad62b3f5be8 | cf227651b9baa0deb5748a678553b145a3ce6803 | refs/heads/master | 2020-06-06T17:48:37.691814 | 2010-04-14T07:22:23 | 2010-04-14T07:22:23 | 34,887,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | h | // WebBrowserDoc.h : interface of the CWebBrowserDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_WEBBROWSERDOC_H__BF63E288_7A20_4994_97CB_BD7648D96FD3__INCLUDED_)
#define AFX_WEBBROWSERDOC_H__BF63E288_7A20_4994_97CB_BD7648D96FD3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CWebBrowserDoc : public CDocument
{
protected: // create from serialization only
CWebBrowserDoc();
DECLARE_DYNCREATE(CWebBrowserDoc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CWebBrowserDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CWebBrowserDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CWebBrowserDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_WEBBROWSERDOC_H__BF63E288_7A20_4994_97CB_BD7648D96FD3__INCLUDED_)
| [
"[email protected]@91cf4698-544a-0410-9e3e-f171e2291419"
] | [
[
[
1,
57
]
]
] |
1bb7dd030af19f8acc8b38ebd39459e7782d4ca0 | 28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc | /mytesgnikrow --username hotga2801/Project/AdaboostFaceDetection/AdaboostFaceDetection/SimpleClassifier.cpp | 13d2b90fb6397b07302e01d40dc9a97d90bfe6a9 | [] | no_license | taicent/mytesgnikrow | 09aed8836e1297a24bef0f18dadd9e9a78ec8e8b | 9264faa662454484ade7137ee8a0794e00bf762f | refs/heads/master | 2020-04-06T04:25:30.075548 | 2011-02-17T13:37:16 | 2011-02-17T13:37:16 | 34,991,750 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | cpp | #include "stdafx.h"
#include <fstream>
#include <vector>
#include <math.h>
using namespace std;
#include "IntImage.h"
#include "SimpleClassifier.h"
#include "AdaBoostClassifier.h"
#include "CascadeClassifier.h"
#include "Global.h"
//#include "FFS.h"
#include "learn.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
void WeakClassifier::ReadFromFile(ifstream& f)
{
f>>m_rThreshold>>m_iParity>>m_iType;
f>>x1>>x2>>x3>>x4>>y1>>y2>>y3>>y4;
f.ignore(256,'\n');
ASSERT(m_iParity == 0 || m_iParity == 1);
ASSERT(m_iType>=0 && m_iType<=4);
}
void WeakClassifier::WriteToFile(ofstream& f) const
{
f<<m_rThreshold<<" ";
f<<m_iParity<<" ";
f<<m_iType<<" ";
f<<x1<<" ";
f<<x2<<" ";
f<<x3<<" ";
f<<x4<<" ";
f<<y1<<" ";
f<<y2<<" ";
f<<y3<<" ";
f<<y4<<" ";
f<<endl;
}
| [
"hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076"
] | [
[
[
1,
43
]
]
] |
e146cf00f0898acd924efe100b3cf06b80dca151 | dadae22098e24c412a8d8d4133c8f009a8a529c9 | /tp1/src/image.h | e88eb410b02201e342dc03be02edb6c5b23ef9cf | [] | no_license | maoueh/PHS4700 | 9fe2bdf96576975b0d81e816c242a8f9d9975fbc | 2c2710fcc5dbe4cd496f7329379ac28af33dc44d | refs/heads/master | 2021-01-22T22:44:17.232771 | 2009-10-06T18:49:30 | 2009-10-06T18:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | h | #ifndef IMAGE_H
#define IMAGE_H
#include "common.h"
class Image
{
public:
virtual ~Image() { };
virtual BOOL load() = 0;
virtual void* getData() = 0;
virtual void getData(BYTE* dataHolder, INT* count) = 0;
virtual STRING getFilename() = 0;
virtual INT getWidth() = 0;
virtual INT getHeight() = 0;
};
#endif | [
"[email protected]"
] | [
[
[
1,
22
]
]
] |
9e13d29ab10909d396a3ad3e799b3ff1ef76405a | e61277f113d65af8c2c1d4dd18e9475df2510e0e | /Source/BEWinFunctions.cpp | 5e2a877d651747432b033799c02b504e43a39269 | [] | no_license | n9yty/BaseElements-Plugin | e2f875502cc17a51420d005365c5256c8488d8a6 | 9136e75e2c31a469eb46828762b230d3a9b2c76d | refs/heads/master | 2020-12-25T17:04:39.258113 | 2011-08-18T23:57:56 | 2011-08-18T23:57:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,686 | cpp | /*
BEWinFunctions.cpp
BaseElements Plug-in
Copyright 2010-2011 Goya. All rights reserved.
For conditions of distribution and use please see the copyright notice in BEPlugin.cpp
http://www.goya.com.au/baseelements/plugin
*/
#include "BEWinFunctions.h"
#include "afxdlgs.h"
#include "Shlwapi.h"
#include "ShlObj.h"
#include "BEPluginGlobalDefines.h"
bool IsFileMakerClipboardType ( const wstring atype );
UINT32 ClipboardOffset ( const wstring atype );
// functions & globals for the dialog callback
LRESULT CALLBACK DialogCallback ( int nCode, WPARAM wParam, LPARAM lParam );
HHOOK g_window_hook;
wstring g_button1_name;
wstring g_button2_name;
wstring g_button3_name;
// clipbaord functions
WStringAutoPtr ClipboardFormats ( void )
{
wstring format_list = L"";
if ( OpenClipboard ( NULL ) ) {
UINT formats = CountClipboardFormats();
UINT next_format = 0;
for ( UINT i = 0 ; i < formats ; i++ ) {
next_format = EnumClipboardFormats ( next_format );
const int max_count = 4096;
wchar_t format_name[max_count];
int name_length = GetClipboardFormatName ( next_format, format_name, max_count );
if ( name_length > 0 ) {
format_list += format_name;
format_list += L"\r";
}
}
CloseClipboard();
}
return WStringAutoPtr ( new wstring ( format_list ) );
} // ClipboardFormats
/*
FileMaker clipboard types for Windows are of the form Mac-XMxx
*/
bool IsFileMakerClipboardType ( const wstring atype )
{
return ( atype.find ( L"Mac-XM" ) == 0 );
}
/*
for FileMaker types the first 4 bytes on the clipboard is the size of the data on the clipboard
*/
UINT32 ClipboardOffset ( const wstring atype )
{
if ( IsFileMakerClipboardType ( atype ) ) {
return 4;
} else {
return 0;
}
}
StringAutoPtr ClipboardData ( WStringAutoPtr atype )
{
char * clipboard_data = NULL;
if ( OpenClipboard ( NULL ) ) {
UINT format_wanted = RegisterClipboardFormat ( atype->c_str() );
if ( IsClipboardFormatAvailable ( format_wanted ) ) {
HGLOBAL memory_handle = GetClipboardData ( format_wanted );
unsigned char * clipboard_contents = (unsigned char *)GlobalLock ( memory_handle );
UINT clipboard_size = GlobalSize ( memory_handle );
clipboard_data = new char [ clipboard_size + 1 ]();
memcpy ( clipboard_data, clipboard_contents, clipboard_size );
GlobalUnlock ( memory_handle );
}
CloseClipboard();
}
if ( !clipboard_data ) {
clipboard_data = new char [ 1 ]();
}
/*
prefix the data to place on the clipboard with the size of the data
*/
UINT32 offset = ClipboardOffset ( *atype );
StringAutoPtr reply ( new string ( clipboard_data + offset ) );
delete[] clipboard_data;
return reply;
} // ClipboardData
bool SetClipboardData ( StringAutoPtr data, WStringAutoPtr atype )
{
bool ok = FALSE;
if ( OpenClipboard ( NULL ) ) {
EmptyClipboard();
UINT32 data_size = data->size();
/*
prefix the data to place on the clipboard with the size of the data
*/
UINT32 offset = ClipboardOffset ( *atype );
UINT32 clipboard_size = data_size + offset;
HGLOBAL memory_handle = GlobalAlloc ( GMEM_SHARE | GMEM_MOVEABLE, clipboard_size );
unsigned char * clipboard_contents = (unsigned char *)GlobalLock ( memory_handle );
if ( IsFileMakerClipboardType ( *atype ) == TRUE ) {
memcpy ( clipboard_contents, &data_size, offset );
}
memcpy ( clipboard_contents + offset, data->c_str(), clipboard_size );
GlobalUnlock ( memory_handle );
UINT format = RegisterClipboardFormat ( atype->c_str() );
if ( SetClipboardData ( format, clipboard_contents ) ) {
ok = TRUE;
}
CloseClipboard();
}
return ok;
} // Set_ClipboardData
// file dialogs
WStringAutoPtr SelectFile ( WStringAutoPtr prompt )
{
CWnd * parent_window = CWnd::FromHandle ( GetActiveWindow() );
CString filter = "All Files (*.*)|*.*||";
CFileDialog file_dialog ( TRUE, NULL, NULL, OFN_HIDEREADONLY, filter, parent_window, 0 );
file_dialog.m_ofn.lpstrTitle = prompt->c_str();
// if the user hasn't cancelled the dialog get the path to the file
wchar_t path[MAX_PATH] = L"";
if ( file_dialog.DoModal() == IDOK ) {
CString file_path = file_dialog.GetPathName();
wcscpy_s ( path, (LPCTSTR)file_path );
}
return WStringAutoPtr ( new wstring ( path ) );
} // SelectFile
WStringAutoPtr SelectFolder ( WStringAutoPtr prompt )
{
BROWSEINFO browse_info = { 0 };
browse_info.hwndOwner = GetActiveWindow();
browse_info.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI | BIF_NONEWFOLDERBUTTON;
browse_info.lpszTitle = prompt->c_str();
LPITEMIDLIST item_list = SHBrowseForFolder ( &browse_info );
// if the user hasn't cancelled the dialog get the path to the folder
wchar_t path[MAX_PATH] = L"";
if ( item_list != 0 ) {
SHGetPathFromIDList ( item_list, path );
}
return WStringAutoPtr ( new wstring ( path ) );
} // SelectFolder
// (customized) alert dialogs
int DisplayDialog ( WStringAutoPtr title, WStringAutoPtr message, WStringAutoPtr button1, WStringAutoPtr button2, WStringAutoPtr button3 )
{
// set the names to be used for each button
g_button1_name.swap ( *button1 );
g_button2_name.swap ( *button2 );
g_button3_name.swap ( *button3 );
// the type of dialog displayed varies depends on the nunmber of buttons required
UINT type = MB_OK;
if ( g_button2_name != L"" ) {
type = MB_OKCANCEL;
if ( g_button3_name != L"" ) {
type = MB_YESNOCANCEL;
}
}
// set the callback so that the custom button names are installed
g_window_hook = SetWindowsHookEx ( WH_CBT, &DialogCallback, 0, GetCurrentThreadId() );
/*
get the user's choice and translate that into a response that matches the equivalent
choice on OS X
*/
int button_clicked = MessageBox ( GetActiveWindow(), message->c_str(), title->c_str(), type );
unsigned long response = 0;
switch ( button_clicked ) {
case IDOK:
case IDYES:
response = kBE_OKButton;
break;
case IDCANCEL:
response = kBE_CancelButton;
break;
case IDNO:
response = kBE_AlternateButton;
break;
}
return response;
} // DisplayDialog
// callback to override the button text on standard alert dialogs
LRESULT CALLBACK DialogCallback ( int nCode, WPARAM wParam, LPARAM lParam )
{
UINT result = 0;
if ( nCode == HCBT_ACTIVATE ) {
HWND dialog = (HWND)wParam;
// set the button text for each button
// the first button can be IDOK or IDYES
if ( GetDlgItem ( dialog, IDOK ) != NULL ) {
result = SetDlgItemText ( dialog, IDOK, g_button1_name.c_str() );
} else if ( GetDlgItem ( dialog, IDYES ) != NULL ) {
result = SetDlgItemText ( dialog, IDYES, g_button1_name.c_str() );
}
if ( GetDlgItem ( dialog, IDCANCEL ) != NULL ) {
result = SetDlgItemText( dialog, IDCANCEL, g_button2_name.c_str() );
}
if ( GetDlgItem ( dialog, IDNO ) != NULL ) {
result = SetDlgItemText ( dialog, IDNO, g_button3_name.c_str() );
}
UnhookWindowsHookEx ( g_window_hook );
} else {
// there may be other installed hooks
CallNextHookEx ( g_window_hook, nCode, wParam, lParam );
}
return result;
} // CBTProc
bool OpenURL ( WStringAutoPtr url )
{
HINSTANCE result = ShellExecute ( NULL, (LPCWSTR)L"open", url->c_str(), NULL, NULL, SW_SHOWNORMAL );
// see http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx
return ( result > (HINSTANCE)32 );
}
| [
"[email protected]"
] | [
[
[
1,
320
]
]
] |
633366572b2a112a51f05470b17871679528e6c1 | 206177d643cb88d0339f6130e764daba1376f4a7 | /cplusplus_code/sources/dlistener.cpp | 28928571f41c016ab9f2ad907e23b52dcc864382 | [] | no_license | mwollenweber/rebridge | aae8b9dfbf985d3264d7e3874079e1f068cda4c1 | 4ca787dd545e8064c926811dc81772a6a8c356d1 | refs/heads/master | 2020-12-24T13:20:11.572283 | 2010-08-01T05:37:02 | 2010-08-01T05:37:02 | 775,487 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,037 | cpp | /*
dlistener.cpp
Author: Adam Pridgen
Summary:
This file contains the generic routines and initialization code
for the debugger extensions dll. Mainly ripped from dbgexts.cpp (Copyright Microsoft).
*/
#include "dlistener.h"
#include "dlistener_windbg.h"
#include "dlistener_eventcb.h"
#include <strsafe.h>
#include <vector>
#include <string>
PDEBUG_CLIENT4 g_ExtClient=NULL, g_cbClient=NULL;
PDEBUG_CONTROL g_ExtControl=NULL;
PDEBUG_SYMBOLS2 g_ExtSymbols=NULL;
PDEBUG_REGISTERS g_ExtRegisters=NULL;
PDEBUG_SYSTEM_OBJECTS g_ExtSystemObjects=NULL;
WINDBG_EXTENSION_APIS ExtensionApis;
ULONG TargetMachine;
BOOL Connected;
// Queries for all debugger interfaces.
extern "C" DllExport HRESULT
ExtQuery(PDEBUG_CLIENT4 Client)
{
//Release_Interfaces();
HRESULT Status;
if((Status = DebugCreate( __uuidof(IDebugClient), (void **)&g_cbClient)) != S_OK){
goto Fail;
}
if ((Status = Client->QueryInterface(__uuidof(IDebugControl),
(void **)&g_ExtControl)) != S_OK)
{
goto Fail;
}
if ((Status = Client->QueryInterface(__uuidof(IDebugSymbols2),
(void **)&g_ExtSymbols)) != S_OK)
{
goto Fail;
}
if ((Status = Client->QueryInterface(__uuidof(IDebugRegisters),
(void **)&g_ExtRegisters)) != S_OK)
{
goto Fail;
}
if ((Status = Client->QueryInterface(__uuidof(IDebugSystemObjects),
(void **)&g_ExtSystemObjects)) != S_OK)
{
goto Fail;
}
g_ExtClient = Client;
if ((Status = Client->QueryInterface(__uuidof(IDebugControl),
(void **)&g_ExtControl)) != S_OK)
{
goto Fail;
}
if ((Status = Client->QueryInterface(__uuidof(IDebugSymbols2),
(void **)&g_ExtSymbols)) != S_OK)
{
goto Fail;
}
if ((Status = Client->QueryInterface(__uuidof(IDebugRegisters),
(void **)&g_ExtRegisters)) != S_OK)
{
goto Fail;
}
return S_OK;
Fail:
ExtRelease();
return Status;
}
void Release_Interfaces()
{
HRESULT Status;
if (g_ExtControl != NULL)
EXT_RELEASE(g_ExtControl);
if (g_ExtSymbols != NULL)
EXT_RELEASE(g_ExtSymbols);
if (g_ExtRegisters != NULL)
EXT_RELEASE(g_ExtRegisters);
if (g_ExtSystemObjects != NULL)
EXT_RELEASE(g_ExtSystemObjects);
}
// Cleans up all debugger interfaces.
void
ExtRelease(void)
{
g_ExtClient = NULL;
Release_Interfaces();
}
// Normal output.
void __cdecl
ExtOut(PCSTR Format, ...)
{
va_list Args;
va_start(Args, Format);
g_ExtControl->OutputVaList(DEBUG_OUTPUT_NORMAL, Format, Args);
va_end(Args);
}
// Error output.
void __cdecl
ExtErr(PCSTR Format, ...)
{
va_list Args;
va_start(Args, Format);
g_ExtControl->OutputVaList(DEBUG_OUTPUT_ERROR, Format, Args);
va_end(Args);
}
// Warning output.
void __cdecl
ExtWarn(PCSTR Format, ...)
{
va_list Args;
va_start(Args, Format);
g_ExtControl->OutputVaList(DEBUG_OUTPUT_WARNING, Format, Args);
va_end(Args);
}
extern "C" DllExport HRESULT
DebugExtensionInitialize(PULONG Version, PULONG Flags)
{
IDebugClient *DebugClient;
PDEBUG_CONTROL DebugControl;
HRESULT Hr;
*Version = DEBUG_EXTENSION_VERSION(1, 0);
*Flags = 0;
Hr = S_OK;
if ((Hr = DebugCreate(__uuidof(IDebugClient),
(void **)&DebugClient)) != S_OK)
{
return Hr;
}
if ((Hr = DebugClient->QueryInterface(__uuidof(IDebugControl),
(void **)&DebugControl)) == S_OK)
{
//
// Get the windbg-style extension APIS
//
ExtensionApis.nSize = sizeof (ExtensionApis);
Hr = DebugControl->GetWindbgExtensionApis64(&ExtensionApis);
DebugControl->Release();
}
DebugClient->Release();
return Hr;
}
extern "C" DllExport void
DebugExtensionNotify(ULONG Notify, ULONG64 Argument)
{
UNREFERENCED_PARAMETER(Argument);
//
// The first time we actually connect to a target
//
if ((Notify == DEBUG_NOTIFY_SESSION_ACCESSIBLE) && (!Connected))
{
IDebugClient *DebugClient;
HRESULT Hr;
PDEBUG_CONTROL DebugControl;
if ((Hr = DebugCreate(__uuidof(IDebugClient),
(void **)&DebugClient)) == S_OK)
{
//
// Get the architecture type.
//
if ((Hr = DebugClient->QueryInterface(__uuidof(IDebugControl),
(void **)&DebugControl)) == S_OK)
{
if ((Hr = DebugControl->GetActualProcessorType(
&TargetMachine)) == S_OK)
{
Connected = TRUE;
}
//NotifyOnTargetAccessible(DebugControl);
DebugControl->Release();
}
DebugClient->Release();
}
}
if (Notify == DEBUG_NOTIFY_SESSION_INACTIVE)
{
Connected = FALSE;
TargetMachine = 0;
}
return;
}
extern "C" DllExport void
DebugExtensionUninitialize(void)
{
return;
}
extern "C" DllExport HRESULT
dlistener(PDEBUG_CLIENT4 Client, PCSTR args) {
HRESULT result = dlistener_handler(Client, args);
ExtRelease();
return result;
}
extern "C" DllExport HRESULT
ida(PDEBUG_CLIENT4 Client, PCSTR args) {
HRESULT result = ida_handler(Client, args);
ExtRelease();
return result;
}
extern "C" DllExport HRESULT
test(PDEBUG_CLIENT4 Client, PCSTR args) {
HRESULT result = test_handler(Client, args);
ExtRelease();
return result;
}
| [
"[email protected]"
] | [
[
[
1,
269
]
]
] |
d5499d8cb8567d6eae5d1f9f3dc5eb1ab7b46f40 | 8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab | /src-ginga-editing/ncl30-generator-cpp/src/RuleBaseGenerator.cpp | 009bbdda5b5411a24a86f5d33f1e35dd335b7918 | [] | no_license | BrunoSSts/ginga-wac | 7436a9815427a74032c9d58028394ccaac45cbf9 | ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c | refs/heads/master | 2020-05-20T22:21:33.645904 | 2011-10-17T12:34:32 | 2011-10-17T12:34:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,554 | cpp | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribuido na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
*******************************************************************************/
/**
* @file RuleBaseGenerator.cpp
* @author Caio Viel
* @date 29-01-10
*/
#include "../include/RuleBaseGenerator.h"
namespace br {
namespace ufscar {
namespace lince {
namespace ncl {
namespace generate {
string RuleBaseGenerator::generateCode() {
string ret = "<ruleBase";
if (id!="") {
ret += " id= \"" + id + "\"";
}
ret += ">\n";
//generico para todas as bases
vector<Base*>* bases = this->getBases();
vector<Base*>::iterator itBases;
itBases = bases->begin();
while (itBases != bases->end()) {
Base* base = *itBases;
ret += "<importBase alias=\"" + this->getBaseAlias(base) + "\" documentURI=\"" + this->getBaseLocation(base) + "\"/>\n";
itBases++;
}
//generico para todas as bases
vector<Rule*>* rules = this->getRules();
vector<Rule*>::iterator it;
it = rules->begin();
while (it != rules->end()) {
Rule* rule = *it;
if (rule->instanceOf("SimpleRule")) {
SimpleRule* simpleRule = (SimpleRule*) rule;
ret += static_cast<SimpleRuleGenerator*>(rule)->generateCode() + "\n";
} else if (rule->instanceOf("CompositeRule")) {
CompositeRule* compositeRule = (CompositeRule*) rule;
ret += static_cast<CompositeRuleGenerator*>(compositeRule)->generateCode() + "\n";
}
it++;
}
ret += "</ruleBase>\n";
return ret;
}
}
}
}
}
}
| [
"[email protected]"
] | [
[
[
1,
105
]
]
] |
70a20d3b2e5bea36beaf9dc04b9f70cb315a9967 | f992ff7d77a993c11768dd509c0307f782a13af0 | /Projekt/src/map/Map.h | 859b9d2f31ae37060df70b6d9afb5d9f7a557c1e | [] | no_license | mariojas/mariusz | 6b0889f3ae623400274ab9448ee8f93556336618 | 965209b0ae0400991b9ceab4c5177b63116302ca | refs/heads/master | 2021-01-23T03:13:01.384598 | 2010-05-03T10:27:47 | 2010-05-03T10:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | h | #ifndef MAP_H
#define MAP_H
#include <vector>
#include "Platform.h"
class Map
{
public:
void setMapPath(char *_mapPath);
void loadPlatforms();
std::vector<Platform> getPlatforms();
void addPlatform(Platform _platform);
private:
char *mapPath;
char *name;
std::vector<Platform> platforms;
BITMAP *map;
BITMAP *bg;
BITMAP *platform_bg;
};
#endif | [
"ryba@ryb-520fb58ee61.(none)"
] | [
[
[
1,
25
]
]
] |
a099a7481b50fffb0aca7fe730fa755458f2efd2 | 1cacbe790f7c6e04ca6b0068c7b2231ed2b827e1 | /Oolong Engine2/Examples/Renderer/Tutorials/08 Shaders Demo (3DShaders.com)/Classes/Shader/3DShaders.src/Xml.cpp | fdf176ca138b0c31a435e2dacc41fcbfea7df76b | [
"BSD-3-Clause"
] | permissive | tianxiao/oolongengine | f3d2d888afb29e19ee93f28223fce6ea48f194ad | 8d80085c65ff3eed548549657e7b472671789e6a | refs/heads/master | 2020-05-30T06:02:32.967513 | 2010-05-05T05:52:03 | 2010-05-05T05:52:03 | 8,245,292 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 17,682 | cpp | //
// Author: Philip Rideout
// Copyright: 2002-2006 3Dlabs Inc. Ltd. All rights reserved.
// License: see 3Dlabs-license.txt
//
#include "App.h"
#include "Tables.h"
#include "Xml.h"
#include "Shaders.h"
#include <expat.h>
#include <cstring>
wxFileName Xml::filename;
std::stack<int> Xml::tags;
std::stack<std::string> Xml::content;
TSlider* Xml::pSlider = 0;
TMotion* Xml::pMotion = 0;
TUniform* Xml::pUniform = 0;
TProgram* Xml::pProgram = 0;
TProgramList* Xml::pProgramList = 0;
const char* Xml::findAttr(const char** attrs, int attr)
{
while (attrs && *attrs) {
if (!strcmp(XmlAttrs[attr - Id::FirstXmlAttr], *attrs))
return *(attrs + 1);
attrs += 2;
}
return 0;
}
void XMLCALL Xml::processStartTag(void* data, const char* tag, const char** attrs)
{
tags.push(findXmlTag(tag));
switch (tags.top()) {
case Id::XmlTagDemo:
pProgramList->SetFolder(filename.GetPath(wxPATH_GET_SEPARATOR) + wxString(findAttr(attrs, Id::XmlAttrFolder)));
break;
case Id::XmlTagProgram:
{
// Retreive the relevent XML attributes.
wxString name = findAttr(attrs, Id::XmlAttrName);
wxString vertex = findAttr(attrs, Id::XmlAttrVertex);
wxString fragment = findAttr(attrs, Id::XmlAttrFragment);
wxString blending = findAttr(attrs, Id::XmlAttrBlending);
wxString reflection = findAttr(attrs, Id::XmlAttrReflection);
wxString depth = findAttr(attrs, Id::XmlAttrDepth);
wxString stressText = findAttr(attrs, Id::XmlAttrStress);
// Set up defaults.
if (vertex.empty())
vertex = name;
if (fragment.empty())
fragment = name;
if (blending.empty())
blending = "off";
if (reflection.empty())
reflection = "on";
if (depth.empty())
depth = "on";
Id stress;
if (stressText.empty())
stress = Id::StressNone;
else
stress = stressText == "vertex" ? Id::StressVertex : Id::StressFragment;
// Form full path strings.
vertex = pProgramList->GetFolder() + "/" + vertex + ".vert";
fragment = pProgramList->GetFolder() + "/" + fragment + ".frag";
// Create the program object.
pProgram = pProgramList->NewShader(name, vertex, fragment, blending == "on", reflection == "on", depth == "on", stress);
break;
}
case Id::XmlTagUniform:
{
if (!pProgram) {
wxGetApp().Errorf("XML error: <uniform> outside <shader>.\n");
break;
}
const char* name = findAttr(attrs, Id::XmlAttrName);
const char* type = findAttr(attrs, Id::XmlAttrType);
pUniform = pProgram->NewUniform(name, type);
break;
}
case Id::XmlTagTangents:
{
if (!pProgram) {
wxGetApp().Errorf("XML error: <tangents> outside <shader>.\n");
break;
}
pProgram->RequiresTangents();
break;
}
case Id::XmlTagBinormals:
{
if (!pProgram) {
wxGetApp().Errorf("XML error: <binormals> outside <shader>.\n");
break;
}
pProgram->RequiresBinormals();
break;
}
case Id::XmlTagMotion:
{
if (!pUniform) {
wxGetApp().Errorf("XML error: <linear> outside <uniform>.\n");
break;
}
if (pUniform->GetType() == 0) {
wxGetApp().Errorf("XML error: <motion> specified in <uniform> with unknown 'type'.\n");
break;
}
const char* type = findAttr(attrs, Id::XmlAttrType);
const char* length = findAttr(attrs, Id::XmlAttrLength);
pMotion = length ? pUniform->NewMotion(type, length) : 0;
pProgram->SetMotion();
break;
}
case Id::XmlTagSlider:
{
if (!pUniform) {
wxGetApp().Errorf("XML error: <linear> outside <uniform>.\n");
break;
}
if (pUniform->GetType() == 0) {
wxGetApp().Errorf("XML error: <slider> specified in <uniform> with unknown 'type'.\n");
break;
}
const char* type = findAttr(attrs, Id::XmlAttrType);
pSlider = pUniform->NewSlider(type);
break;
}
case Id::XmlTagSilhouette:
{
if (!pProgram) {
wxGetApp().Errorf("XML error: <silhouette> outside <program>.\n");
break;
}
pProgram->SetSilhouette();
break;
}
case Id::XmlTagTextures:
{
const char* stage = findAttr(attrs, Id::XmlAttrStage);
if (stage)
pProgram->TextureStage(atoi(stage));
const char* mipmap = findAttr(attrs, Id::XmlAttrMipmap);
if (mipmap)
pProgram->Mipmap(atoi(mipmap));
break;
}
case Id::XmlTagModels:
{
const char* lod = findAttr(attrs, Id::XmlAttrLod);
if (lod)
pProgram->Lod(atoi(lod));
break;
}
}
content.push(std::string());
}
void XMLCALL Xml::processEndTag(void* data, const char* tag)
{
const char* pData = content.top().c_str();
switch (tags.top()) {
case Id::XmlTagUniform:
{
if (!pUniform) {
wxGetApp().Errorf("XML error: <uniform> end tag without corresponding start tag.\n");
break;
}
if (pSlider)
pUniform->UpdateSlider();
float x, y, z, w;
int i, j, k, h;
if (!pUniform->GetType()) {
if (strchr(pData, '.') || strchr(pData, 'e')) {
int components = sscanf(pData, "%f %f %f %f", &x, &y, &z, &w);
switch (components)
{
case 1: pUniform->SetType(Id::UniformTypeFloat); break;
case 2: pUniform->SetType(Id::UniformTypeVec2); break;
case 3: pUniform->SetType(Id::UniformTypeVec3); break;
case 4: pUniform->SetType(Id::UniformTypeVec4); break;
}
} else {
int components = sscanf(pData, "%d %d %d %d", &i, &j, &k, &h);
switch (components) {
case 1: pUniform->SetType(Id::UniformTypeInt); break;
case 2: pUniform->SetType(Id::UniformTypeIvec2); break;
case 3: pUniform->SetType(Id::UniformTypeIvec3); break;
case 4: pUniform->SetType(Id::UniformTypeIvec4); break;
}
}
}
switch (pUniform->GetType()) {
case Id::UniformTypeFloat: if (sscanf(pData, "%f", &x) > 0) pUniform->Set(x); break;
case Id::UniformTypeVec2: if (sscanf(pData, "%f %f", &x, &y) > 0) pUniform->Set(x, y); break;
case Id::UniformTypeVec3: if (sscanf(pData, "%f %f %f", &x, &y, &z) > 0) pUniform->Set(x, y, z); break;
case Id::UniformTypeVec4: if (sscanf(pData, "%f %f %f %f", &x, &y, &z, &w) > 0) pUniform->Set(x, y, z, w); break;
case Id::UniformTypeInt: if (sscanf(pData, "%d", &i) > 0) pUniform->Set(i); break;
case Id::UniformTypeIvec2: if (sscanf(pData, "%d %d", &i, &j) > 0) pUniform->Set(i, j); break;
case Id::UniformTypeIvec3: if (sscanf(pData, "%d %d %d", &i, &j, &k) > 0) pUniform->Set(i, j, k); break;
case Id::UniformTypeIvec4: if (sscanf(pData, "%d %d %d %d", &i, &j, &k, &h) > 0) pUniform->Set(i, j, k, h); break;
case Id::UniformTypeMat2:
{
mat2 m;
sscanf(pData, "%f %f", &x, &y); m.data[0] = x; m.data[1] = y;
sscanf(pData, "%f %f", &x, &y); m.data[2] = x; m.data[3] = y;
pUniform->Set(m);
}
case Id::UniformTypeMat3:
{
mat3 m;
sscanf(pData, "%f %f %f", &x, &y, &z); m.data[0] = x; m.data[1] = y; m.data[2] = z;
sscanf(pData, "%f %f %f", &x, &y, &z); m.data[3] = x; m.data[4] = y; m.data[5] = z;
sscanf(pData, "%f %f %f", &x, &y, &z); m.data[6] = x; m.data[7] = y; m.data[8] = z;
pUniform->Set(m);
}
case Id::UniformTypeMat4:
{
mat4 m;
sscanf(pData, "%f %f %f %f", &x, &y, &z, &w); m.data[0] = x; m.data[1] = y; m.data[2] = z; m.data[3] = w;
sscanf(pData, "%f %f %f %f", &x, &y, &z, &w); m.data[4] = x; m.data[5] = y; m.data[6] = z; m.data[7] = w;
sscanf(pData, "%f %f %f %f", &x, &y, &z, &w); m.data[8] = x; m.data[9] = y; m.data[10] = z; m.data[11] = w;
sscanf(pData, "%f %f %f %f", &x, &y, &z, &w); m.data[12] = x; m.data[13] = y; m.data[14] = z; m.data[15] = w;
pUniform->Set(m);
}
}
pUniform->UpdateDuration();
if (pSlider) {
for (int c = 0; c < pUniform->NumComponents(); ++c)
pUniform->SetSlider(pUniform->GetSlider(c), c);
pSlider = 0;
}
break;
}
case Id::XmlTagMotion:
{
if (!pMotion)
break;
TUniformValue& start = pMotion->start;
TUniformValue& stop = pMotion->stop;
switch (pUniform->GetType()) {
case Id::UniformTypeFloat:
sscanf(pData, "%f %f", &start.f[0], &stop.f[0]);
break;
case Id::UniformTypeVec2:
sscanf(pData, "%f %f %f %f", &start.f[0], &start.f[1], &stop.f[0], &stop.f[1]);
break;
case Id::UniformTypeVec3:
sscanf(pData, "%f %f %f %f %f %f", &start.f[0], &start.f[1], &start.f[2],
&stop.f[0], &stop.f[1], &stop.f[2]);
break;
case Id::UniformTypeVec4:
sscanf(pData, "%f %f %f %f %f %f %f %f", &start.f[0], &start.f[1],
&start.f[2], &start.f[3], &stop.f[0], &stop.f[1], &stop.f[2], &stop.f[3]);
break;
case Id::UniformTypeInt:
sscanf(pData, "%d %d", &start.i[0], &stop.i[0]);
break;
case Id::UniformTypeIvec2:
sscanf(pData, "%d %d %d %d", &start.i[0], &start.i[1], &stop.i[0], &stop.i[1]);
break;
case Id::UniformTypeIvec3:
sscanf(pData, "%d %d %d %d %d %d", &start.i[0], &start.i[1], &start.i[2],
&stop.i[0], &stop.i[1], &stop.i[2]);
break;
case Id::UniformTypeIvec4:
sscanf(pData, "%d %d %d %d %d %d %d %d", &start.i[0], &start.i[1], &start.i[2],
&start.i[3], &stop.i[0], &stop.i[1], &stop.i[2], &stop.i[3]);
break;
case Id::UniformTypeMat2:
case Id::UniformTypeMat3:
case Id::UniformTypeMat4:
wxGetApp().Errorf("XML error: matrices not yet implemented.\n");
break;
}
break;
}
case Id::XmlTagSlider:
{
if (!pSlider) {
wxGetApp().Errorf("XML error: invalid slider.\n");
break;
}
TUniformValue& current = pSlider->current;
TUniformValue& start = pSlider->start;
TUniformValue& stop = pSlider->stop;
switch (pUniform->GetType()) {
case Id::UniformTypeFloat:
sscanf(pData, "%f %f", &start.f[0], &stop.f[0]);
break;
case Id::UniformTypeVec2:
sscanf(pData, "%f %f %f %f", &start.f[0], &start.f[1], &stop.f[0], &stop.f[1]);
break;
case Id::UniformTypeVec3:
sscanf(pData, "%f %f %f %f %f %f", &start.f[0], &start.f[1], &start.f[2],
&stop.f[0], &stop.f[1], &stop.f[2]);
break;
case Id::UniformTypeVec4:
sscanf(pData, "%f %f %f %f %f %f %f %f", &start.f[0], &start.f[1],
&start.f[2], &start.f[3], &stop.f[0], &stop.f[1], &stop.f[2], &stop.f[3]);
break;
case Id::UniformTypeInt:
sscanf(pData, "%d %d", &start.i[0], &stop.i[0]);
break;
case Id::UniformTypeIvec2:
sscanf(pData, "%d %d %d %d", &start.i[0], &start.i[1], &stop.i[0], &stop.i[1]);
break;
case Id::UniformTypeIvec3:
sscanf(pData, "%d %d %d %d %d %d", &start.i[0], &start.i[1], &start.i[2],
&stop.i[0], &stop.i[1], &stop.i[2]);
break;
case Id::UniformTypeIvec4:
sscanf(pData, "%d %d %d %d %d %d %d %d", &start.i[0], &start.i[1], &start.i[2],
&start.i[3], &stop.i[0], &stop.i[1], &stop.i[2], &stop.i[3]);
break;
case Id::UniformTypeMat2:
case Id::UniformTypeMat3:
case Id::UniformTypeMat4:
wxGetApp().Errorf("XML error: matrices not yet implemented.\n");
break;
}
if (pUniform->IsInteger()) {
for (int c = 0; c < pUniform->NumComponents(); ++c)
current.i[c] = (start.i[c] + stop.i[c]) / 2;
} else {
for (int c = 0; c < pUniform->NumComponents(); ++c)
current.f[c] = (start.f[c] + stop.f[c]) / 2;
}
break;
}
case Id::XmlTagModels:
{
if (!pProgram)
return;
// Parse the list of models. Each model is seperated by whitespace.
while (pData && *pData) {
char* whitespace = strpbrk(pData, " \t\n");
if (whitespace)
*whitespace = 0;
int length = strlen(pData);
if (!length)
break;
if (*pData == '-')
pProgram->SubtractModel(pData + 1);
else
pProgram->AddModel(pData);
if (!whitespace)
break;
pData = whitespace + 1;
while (*pData && pData == strpbrk(pData, " \t\n"))
++pData;
}
break;
}
case Id::XmlTagTextures:
{
if (!pProgram)
return;
// Parse the list of textures. Each texture is seperated by whitespace.
while (pData && *pData) {
char* whitespace = strpbrk(pData, " \t\n");
if (whitespace)
*whitespace = 0;
int length = strlen(pData);
if (!length)
break;
if (*pData == '-')
pProgram->SubtractTexture(pData + 1);
else
pProgram->AddTexture(pData);
if (!whitespace)
break;
pData = whitespace + 1;
while (*pData && pData == strpbrk(pData, " \t\n"))
++pData;
}
break;
}
}
tags.pop();
content.pop();
}
void XMLCALL Xml::processData(void* user, const XML_Char* data, int length)
{
if (!tags.empty())
content.top().insert(content.top().length(), data, length);
}
bool Xml::Parse(const wxFileName& filename)
{
Xml::filename = filename;
XML_Parser parser = XML_ParserCreate(0);
XML_SetElementHandler(parser, processStartTag, processEndTag);
XML_SetCharacterDataHandler(parser, processData);
FILE* xml = fopen(filename.GetFullPath(), "r");
if (!xml)
return false;
char buffer[1024];
int done;
do {
fgets(buffer, sizeof(buffer), xml);
done = feof(xml);
if (!done && XML_Parse(parser, buffer, strlen(buffer), 0) == XML_STATUS_ERROR)
wxGetApp().Errorf("XML parse error at line %d:\n%s\n",
XML_GetCurrentLineNumber(parser),
XML_ErrorString(XML_GetErrorCode(parser)));
} while (!done);
fclose(xml);
XML_ParserFree(parser);
return true;
}
| [
"mozeal@7fa7efda-f44a-0410-a86a-c1fddb4bcab7"
] | [
[
[
1,
481
]
]
] |
f07d07048b965275e8f0cc43b383ec4d076b0889 | bfe8eca44c0fca696a0031a98037f19a9938dd26 | /libjingle-0.4.0/talk/base/criticalsection.h | aeb1ad8e452af8cef0bdfd8a47242763ba082853 | [
"BSD-3-Clause"
] | permissive | luge/foolject | a190006bc0ed693f685f3a8287ea15b1fe631744 | 2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c | refs/heads/master | 2021-01-10T07:41:06.726526 | 2011-01-21T10:25:22 | 2011-01-21T10:25:22 | 36,303,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,479 | h | /*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TALK_BASE_CRITICALSECTION_H__
#define TALK_BASE_CRITICALSECTION_H__
#ifdef WIN32
#include "talk/base/win32.h"
#endif
#ifdef POSIX
#include <pthread.h>
#endif
#ifdef _DEBUG
#define CS_TRACK_OWNER 1
#endif // _DEBUG
#if CS_TRACK_OWNER
#define TRACK_OWNER(x) x
#else // !CS_TRACK_OWNER
#define TRACK_OWNER(x)
#endif // !CS_TRACK_OWNER
namespace talk_base {
#ifdef WIN32
class CriticalSection {
public:
CriticalSection() {
InitializeCriticalSection(&crit_);
// Windows docs say 0 is not a valid thread id
TRACK_OWNER(thread_ = 0);
}
~CriticalSection() {
DeleteCriticalSection(&crit_);
}
void Enter() {
EnterCriticalSection(&crit_);
TRACK_OWNER(thread_ = GetCurrentThreadId());
}
void Leave() {
TRACK_OWNER(thread_ = 0);
LeaveCriticalSection(&crit_);
}
#if CS_TRACK_OWNER
bool CurrentThreadIsOwner() const { return thread_ == GetCurrentThreadId(); }
#endif // CS_TRACK_OWNER
private:
CRITICAL_SECTION crit_;
TRACK_OWNER(DWORD thread_); // The section's owning thread id
};
#endif // WIN32
#ifdef POSIX
class CriticalSection {
public:
CriticalSection() {
pthread_mutexattr_t mutex_attribute;
pthread_mutexattr_init(&mutex_attribute);
pthread_mutexattr_settype(&mutex_attribute, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex_, &mutex_attribute);
}
~CriticalSection() {
pthread_mutex_destroy(&mutex_);
}
void Enter() {
pthread_mutex_lock(&mutex_);
}
void Leave() {
pthread_mutex_unlock(&mutex_);
}
private:
pthread_mutex_t mutex_;
};
#endif // POSIX
// CritScope, for serializing exection through a scope
class CritScope {
public:
CritScope(CriticalSection *pcrit) {
pcrit_ = pcrit;
pcrit_->Enter();
}
~CritScope() {
pcrit_->Leave();
}
private:
CriticalSection *pcrit_;
};
} // namespace talk_base
#endif // TALK_BASE_CRITICALSECTION_H__
| [
"[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30"
] | [
[
[
1,
121
]
]
] |
98d7d94356418306c98e31e20c927b2495e2e8a8 | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/GameDLL/AmmoPickup.h | 86ebbaff284e87768e2195dd073fc0fad39fa5cd | [] | no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,738 | h | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2004.
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: AmmoPickup Implementation
-------------------------------------------------------------------------
History:
- 9:2:2006 17:09 : Created by Márcio Martins
*************************************************************************/
#ifndef __AMMOPICKUP_H__
#define __AMMOPICKUP_H__
#if _MSC_VER > 1000
# pragma once
#endif
#include <IItemSystem.h>
#include "Weapon.h"
class CAmmoPickup :
public CWeapon
{
public:
virtual void PostInit( IGameObject * pGameObject );
virtual bool CanUse(EntityId userId) const;
virtual bool CanPickUp(EntityId pickerId) const;
virtual void SerializeSpawnInfo( TSerialize ser );
virtual ISerializableInfoPtr GetSpawnInfo();
virtual void PickUp(EntityId pickerId, bool sound, bool select, bool keepHistory);
virtual bool CheckAmmoRestrictions(EntityId pickerId);
virtual void GetMemoryStatistics(ICrySizer * s) { s->Add(*this);
s->Add(m_pickup_sound);
s->Add(m_modelName);
CWeapon::GetMemoryStatistics(s); }
protected:
virtual bool ReadItemParams(const IItemParamsNode *root);
private:
//Special case for grenades (might need to switch firemode)
void ShouldSwitchGrenade(IEntityClass* pClass);
void OnIncendiaryAmmoPickedUp(IEntityClass *pClass, int count);
ItemString m_modelName;
ItemString m_ammoName;
int m_ammoCount;
ItemString m_pickup_sound;
};
#endif // __AMMOPICKUP_H__ | [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
] | [
[
[
1,
50
],
[
52,
53
],
[
56,
60
]
],
[
[
51,
51
],
[
54,
55
]
]
] |
a142deb8dddb38d21afa13248f4c0dab41c31dab | 5c4e36054f0752a610ad149dfd81e6f35ccb37a1 | /libs/src2.75/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp | 5bf0f335baa11ccac0154c02d765ac0f821271cc | [] | no_license | Akira-Hayasaka/ofxBulletPhysics | 4141dc7b6dff7e46b85317b0fe7d2e1f8896b2e4 | 5e45da80bce2ed8b1f12de9a220e0c1eafeb7951 | refs/heads/master | 2016-09-15T23:11:01.354626 | 2011-09-22T04:11:35 | 2011-09-22T04:11:35 | 1,152,090 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,767 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///Specialized capsule-capsule collision algorithm has been added for Bullet 2.75 release to increase ragdoll performance
///If you experience problems with capsule-capsule collision, try to define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER and report it in the Bullet forums
///with reproduction case
//define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER 1
#include "btConvexConvexAlgorithm.h"
//#include <stdio.h>
#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btCapsuleShape.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
///////////
static SIMD_FORCE_INLINE void segmentsClosestPoints(
btVector3& ptsVector,
btVector3& offsetA,
btVector3& offsetB,
btScalar& tA, btScalar& tB,
const btVector3& translation,
const btVector3& dirA, btScalar hlenA,
const btVector3& dirB, btScalar hlenB )
{
// compute the parameters of the closest points on each line segment
btScalar dirA_dot_dirB = btDot(dirA,dirB);
btScalar dirA_dot_trans = btDot(dirA,translation);
btScalar dirB_dot_trans = btDot(dirB,translation);
btScalar denom = 1.0f - dirA_dot_dirB * dirA_dot_dirB;
if ( denom == 0.0f ) {
tA = 0.0f;
} else {
tA = ( dirA_dot_trans - dirB_dot_trans * dirA_dot_dirB ) / denom;
if ( tA < -hlenA )
tA = -hlenA;
else if ( tA > hlenA )
tA = hlenA;
}
tB = tA * dirA_dot_dirB - dirB_dot_trans;
if ( tB < -hlenB ) {
tB = -hlenB;
tA = tB * dirA_dot_dirB + dirA_dot_trans;
if ( tA < -hlenA )
tA = -hlenA;
else if ( tA > hlenA )
tA = hlenA;
} else if ( tB > hlenB ) {
tB = hlenB;
tA = tB * dirA_dot_dirB + dirA_dot_trans;
if ( tA < -hlenA )
tA = -hlenA;
else if ( tA > hlenA )
tA = hlenA;
}
// compute the closest points relative to segment centers.
offsetA = dirA * tA;
offsetB = dirB * tB;
ptsVector = translation - offsetA + offsetB;
}
static SIMD_FORCE_INLINE btScalar capsuleCapsuleDistance(
btVector3& normalOnB,
btVector3& pointOnB,
btScalar capsuleLengthA,
btScalar capsuleRadiusA,
btScalar capsuleLengthB,
btScalar capsuleRadiusB,
int capsuleAxisA,
int capsuleAxisB,
const btTransform& transformA,
const btTransform& transformB,
btScalar distanceThreshold )
{
btVector3 directionA = transformA.getBasis().getColumn(capsuleAxisA);
btVector3 translationA = transformA.getOrigin();
btVector3 directionB = transformB.getBasis().getColumn(capsuleAxisB);
btVector3 translationB = transformB.getOrigin();
// translation between centers
btVector3 translation = translationB - translationA;
// compute the closest points of the capsule line segments
btVector3 ptsVector; // the vector between the closest points
btVector3 offsetA, offsetB; // offsets from segment centers to their closest points
btScalar tA, tB; // parameters on line segment
segmentsClosestPoints( ptsVector, offsetA, offsetB, tA, tB, translation,
directionA, capsuleLengthA, directionB, capsuleLengthB );
btScalar distance = ptsVector.length() - capsuleRadiusA - capsuleRadiusB;
if ( distance > distanceThreshold )
return distance;
btScalar lenSqr = ptsVector.length2();
if (lenSqr<= (SIMD_EPSILON*SIMD_EPSILON))
{
//degenerate case where 2 capsules are likely at the same location: take a vector tangential to 'directionA'
btVector3 q;
btPlaneSpace1(directionA,normalOnB,q);
} else
{
// compute the contact normal
normalOnB = ptsVector*-btRecipSqrt(lenSqr);
}
pointOnB = transformB.getOrigin()+offsetB + normalOnB * capsuleRadiusB;
return distance;
}
//////////
btConvexConvexAlgorithm::CreateFunc::CreateFunc(btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver)
{
m_numPerturbationIterations = 0;
m_minimumPointsPerturbationThreshold = 3;
m_simplexSolver = simplexSolver;
m_pdSolver = pdSolver;
}
btConvexConvexAlgorithm::CreateFunc::~CreateFunc()
{
}
btConvexConvexAlgorithm::btConvexConvexAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver,int numPerturbationIterations, int minimumPointsPerturbationThreshold)
: btActivatingCollisionAlgorithm(ci,body0,body1),
m_simplexSolver(simplexSolver),
m_pdSolver(pdSolver),
m_ownManifold (false),
m_manifoldPtr(mf),
m_lowLevelOfDetail(false),
#ifdef USE_SEPDISTANCE_UTIL2
m_sepDistance((static_cast<btConvexShape*>(body0->getCollisionShape()))->getAngularMotionDisc(),
(static_cast<btConvexShape*>(body1->getCollisionShape()))->getAngularMotionDisc()),
#endif
m_numPerturbationIterations(numPerturbationIterations),
m_minimumPointsPerturbationThreshold(minimumPointsPerturbationThreshold)
{
(void)body0;
(void)body1;
}
btConvexConvexAlgorithm::~btConvexConvexAlgorithm()
{
if (m_ownManifold)
{
if (m_manifoldPtr)
m_dispatcher->releaseManifold(m_manifoldPtr);
}
}
void btConvexConvexAlgorithm ::setLowLevelOfDetail(bool useLowLevel)
{
m_lowLevelOfDetail = useLowLevel;
}
struct btPerturbedContactResult : public btManifoldResult
{
btManifoldResult* m_originalManifoldResult;
btTransform m_transformA;
btTransform m_transformB;
btTransform m_unPerturbedTransform;
bool m_perturbA;
btIDebugDraw* m_debugDrawer;
btPerturbedContactResult(btManifoldResult* originalResult,const btTransform& transformA,const btTransform& transformB,const btTransform& unPerturbedTransform,bool perturbA,btIDebugDraw* debugDrawer)
:m_originalManifoldResult(originalResult),
m_transformA(transformA),
m_transformB(transformB),
m_perturbA(perturbA),
m_unPerturbedTransform(unPerturbedTransform),
m_debugDrawer(debugDrawer)
{
}
virtual ~ btPerturbedContactResult()
{
}
virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar orgDepth)
{
btVector3 endPt,startPt;
btScalar newDepth;
btVector3 newNormal;
if (m_perturbA)
{
btVector3 endPtOrg = pointInWorld + normalOnBInWorld*orgDepth;
endPt = (m_unPerturbedTransform*m_transformA.inverse())(endPtOrg);
newDepth = (endPt - pointInWorld).dot(normalOnBInWorld);
startPt = endPt+normalOnBInWorld*newDepth;
} else
{
endPt = pointInWorld + normalOnBInWorld*orgDepth;
startPt = (m_unPerturbedTransform*m_transformB.inverse())(pointInWorld);
newDepth = (endPt - startPt).dot(normalOnBInWorld);
}
//#define DEBUG_CONTACTS 1
#ifdef DEBUG_CONTACTS
m_debugDrawer->drawLine(startPt,endPt,btVector3(1,0,0));
m_debugDrawer->drawSphere(startPt,0.05,btVector3(0,1,0));
m_debugDrawer->drawSphere(endPt,0.05,btVector3(0,0,1));
#endif //DEBUG_CONTACTS
m_originalManifoldResult->addContactPoint(normalOnBInWorld,startPt,newDepth);
}
};
extern btScalar gContactBreakingThreshold;
//
// Convex-Convex collision algorithm
//
void btConvexConvexAlgorithm ::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
if (!m_manifoldPtr)
{
//swapped?
m_manifoldPtr = m_dispatcher->getNewManifold(body0,body1);
m_ownManifold = true;
}
resultOut->setPersistentManifold(m_manifoldPtr);
//comment-out next line to test multi-contact generation
//resultOut->getPersistentManifold()->clearManifold();
btConvexShape* min0 = static_cast<btConvexShape*>(body0->getCollisionShape());
btConvexShape* min1 = static_cast<btConvexShape*>(body1->getCollisionShape());
btVector3 normalOnB;
btVector3 pointOnBWorld;
#ifndef BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
if ((min0->getShapeType() == CAPSULE_SHAPE_PROXYTYPE) && (min1->getShapeType() == CAPSULE_SHAPE_PROXYTYPE))
{
btCapsuleShape* capsuleA = (btCapsuleShape*) min0;
btCapsuleShape* capsuleB = (btCapsuleShape*) min1;
btVector3 localScalingA = capsuleA->getLocalScaling();
btVector3 localScalingB = capsuleB->getLocalScaling();
btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,capsuleA->getHalfHeight(),capsuleA->getRadius(),
capsuleB->getHalfHeight(),capsuleB->getRadius(),capsuleA->getUpAxis(),capsuleB->getUpAxis(),
body0->getWorldTransform(),body1->getWorldTransform(),threshold);
if (dist<threshold)
{
btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
}
resultOut->refreshContactPoints();
return;
}
#endif //BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
#ifdef USE_SEPDISTANCE_UTIL2
m_sepDistance.updateSeparatingDistance(body0->getWorldTransform(),body1->getWorldTransform());
if (!dispatchInfo.m_useConvexConservativeDistanceUtil || m_sepDistance.getConservativeSeparatingDistance()<=0.f)
#endif //USE_SEPDISTANCE_UTIL2
{
btGjkPairDetector::ClosestPointInput input;
btGjkPairDetector gjkPairDetector(min0,min1,m_simplexSolver,m_pdSolver);
//TODO: if (dispatchInfo.m_useContinuous)
gjkPairDetector.setMinkowskiA(min0);
gjkPairDetector.setMinkowskiB(min1);
#ifdef USE_SEPDISTANCE_UTIL2
if (dispatchInfo.m_useConvexConservativeDistanceUtil)
{
input.m_maximumDistanceSquared = BT_LARGE_FLOAT;
} else
#endif //USE_SEPDISTANCE_UTIL2
{
input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactBreakingThreshold();
input.m_maximumDistanceSquared*= input.m_maximumDistanceSquared;
}
input.m_stackAlloc = dispatchInfo.m_stackAllocator;
input.m_transformA = body0->getWorldTransform();
input.m_transformB = body1->getWorldTransform();
gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
btVector3 v0,v1;
btVector3 sepNormalWorldSpace;
#ifdef USE_SEPDISTANCE_UTIL2
btScalar sepDist = 0.f;
if (dispatchInfo.m_useConvexConservativeDistanceUtil)
{
sepDist = gjkPairDetector.getCachedSeparatingDistance();
if (sepDist>SIMD_EPSILON)
{
sepDist += dispatchInfo.m_convexConservativeDistanceThreshold;
//now perturbe directions to get multiple contact points
sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis().normalized();
btPlaneSpace1(sepNormalWorldSpace,v0,v1);
}
}
#endif //USE_SEPDISTANCE_UTIL2
//now perform 'm_numPerturbationIterations' collision queries with the perturbated collision objects
//perform perturbation when more then 'm_minimumPointsPerturbationThreshold' points
if (resultOut->getPersistentManifold()->getNumContacts() < m_minimumPointsPerturbationThreshold)
{
int i;
bool perturbeA = true;
const btScalar angleLimit = 0.125f * SIMD_PI;
btScalar perturbeAngle;
btScalar radiusA = min0->getAngularMotionDisc();
btScalar radiusB = min1->getAngularMotionDisc();
if (radiusA < radiusB)
{
perturbeAngle = gContactBreakingThreshold /radiusA;
perturbeA = true;
} else
{
perturbeAngle = gContactBreakingThreshold / radiusB;
perturbeA = false;
}
if ( perturbeAngle > angleLimit )
perturbeAngle = angleLimit;
btTransform unPerturbedTransform;
if (perturbeA)
{
unPerturbedTransform = input.m_transformA;
} else
{
unPerturbedTransform = input.m_transformB;
}
for ( i=0;i<m_numPerturbationIterations;i++)
{
btQuaternion perturbeRot(v0,perturbeAngle);
btScalar iterationAngle = i*(SIMD_2_PI/btScalar(m_numPerturbationIterations));
btQuaternion rotq(sepNormalWorldSpace,iterationAngle);
if (perturbeA)
{
input.m_transformA.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body0->getWorldTransform().getBasis());
input.m_transformB = body1->getWorldTransform();
#ifdef DEBUG_CONTACTS
dispatchInfo.m_debugDraw->drawTransform(input.m_transformA,10.0);
#endif //DEBUG_CONTACTS
} else
{
input.m_transformA = body0->getWorldTransform();
input.m_transformB.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body1->getWorldTransform().getBasis());
#ifdef DEBUG_CONTACTS
dispatchInfo.m_debugDraw->drawTransform(input.m_transformB,10.0);
#endif
}
btPerturbedContactResult perturbedResultOut(resultOut,input.m_transformA,input.m_transformB,unPerturbedTransform,perturbeA,dispatchInfo.m_debugDraw);
gjkPairDetector.getClosestPoints(input,perturbedResultOut,dispatchInfo.m_debugDraw);
}
}
#ifdef USE_SEPDISTANCE_UTIL2
if (dispatchInfo.m_useConvexConservativeDistanceUtil && (sepDist>SIMD_EPSILON))
{
m_sepDistance.initSeparatingDistance(gjkPairDetector.getCachedSeparatingAxis(),sepDist,body0->getWorldTransform(),body1->getWorldTransform());
}
#endif //USE_SEPDISTANCE_UTIL2
}
if (m_ownManifold)
{
resultOut->refreshContactPoints();
}
}
bool disableCcd = false;
btScalar btConvexConvexAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
(void)resultOut;
(void)dispatchInfo;
///Rather then checking ALL pairs, only calculate TOI when motion exceeds threshold
///Linear motion for one of objects needs to exceed m_ccdSquareMotionThreshold
///col0->m_worldTransform,
btScalar resultFraction = btScalar(1.);
btScalar squareMot0 = (col0->getInterpolationWorldTransform().getOrigin() - col0->getWorldTransform().getOrigin()).length2();
btScalar squareMot1 = (col1->getInterpolationWorldTransform().getOrigin() - col1->getWorldTransform().getOrigin()).length2();
if (squareMot0 < col0->getCcdSquareMotionThreshold() &&
squareMot1 < col1->getCcdSquareMotionThreshold())
return resultFraction;
if (disableCcd)
return btScalar(1.);
//An adhoc way of testing the Continuous Collision Detection algorithms
//One object is approximated as a sphere, to simplify things
//Starting in penetration should report no time of impact
//For proper CCD, better accuracy and handling of 'allowed' penetration should be added
//also the mainloop of the physics should have a kind of toi queue (something like Brian Mirtich's application of Timewarp for Rigidbodies)
/// Convex0 against sphere for Convex1
{
btConvexShape* convex0 = static_cast<btConvexShape*>(col0->getCollisionShape());
btSphereShape sphere1(col1->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
btConvexCast::CastResult result;
btVoronoiSimplexSolver voronoiSimplex;
//SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
///Simplification, one object is simplified as a sphere
btGjkConvexCast ccd1( convex0 ,&sphere1,&voronoiSimplex);
//ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
{
//store result.m_fraction in both bodies
if (col0->getHitFraction()> result.m_fraction)
col0->setHitFraction( result.m_fraction );
if (col1->getHitFraction() > result.m_fraction)
col1->setHitFraction( result.m_fraction);
if (resultFraction > result.m_fraction)
resultFraction = result.m_fraction;
}
}
/// Sphere (for convex0) against Convex1
{
btConvexShape* convex1 = static_cast<btConvexShape*>(col1->getCollisionShape());
btSphereShape sphere0(col0->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
btConvexCast::CastResult result;
btVoronoiSimplexSolver voronoiSimplex;
//SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
///Simplification, one object is simplified as a sphere
btGjkConvexCast ccd1(&sphere0,convex1,&voronoiSimplex);
//ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
{
//store result.m_fraction in both bodies
if (col0->getHitFraction() > result.m_fraction)
col0->setHitFraction( result.m_fraction);
if (col1->getHitFraction() > result.m_fraction)
col1->setHitFraction( result.m_fraction);
if (resultFraction > result.m_fraction)
resultFraction = result.m_fraction;
}
}
return resultFraction;
}
| [
"[email protected]"
] | [
[
[
1,
565
]
]
] |
74a6264573b614a0a635d2c545cae58095a3d3d8 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/include/MyGUI_SimpleText.h | 884358e7ed58530395240f2c9672731473e0cf41 | [] | no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,279 | h | /*!
@file
@author Albert Semenov
@date 02/2008
*/
/*
This file is part of MyGUI.
MyGUI 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.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_SIMPLE_TEXT_H__
#define __MYGUI_SIMPLE_TEXT_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_XmlDocument.h"
#include "MyGUI_Types.h"
#include "MyGUI_ISubWidgetText.h"
#include "MyGUI_EditText.h"
namespace MyGUI
{
class MYGUI_EXPORT SimpleText : public EditText
{
MYGUI_RTTI_DERIVED( SimpleText )
public:
SimpleText();
virtual ~SimpleText();
virtual void setViewOffset(const IntPoint& _point);
virtual void doRender();
};
} // namespace MyGUI
#endif // __MYGUI_SIMPLE_TEXT_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
50
]
]
] |
6c0cd9dd3bcbd135ea05768d6aa973bdf62d6b61 | 8aa65aef3daa1a52966b287ffa33a3155e48cc84 | /Source/3rdparty/Bullet/src/BulletCollision/CollisionShapes/btConvexPointCloudShape.cpp | 11007cdd7c372ac77cea3f64082d097d7c08209d | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jitrc/p3d | da2e63ef4c52ccb70023d64316cbd473f3bd77d9 | b9943c5ee533ddc3a5afa6b92bad15a864e40e1e | refs/heads/master | 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,961 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btConvexPointCloudShape.h"
#include "BulletCollision/CollisionShapes/btCollisionMargin.h"
#include "LinearMath/btQuaternion.h"
void btConvexPointCloudShape::setLocalScaling(const btVector3& scaling)
{
m_localScaling = scaling;
recalcLocalAabb();
}
#ifndef __SPU__
btVector3 btConvexPointCloudShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const
{
btVector3 supVec(btScalar(0.),btScalar(0.),btScalar(0.));
btScalar newDot,maxDot = btScalar(-1e30);
btVector3 vec = vec0;
btScalar lenSqr = vec.length2();
if (lenSqr < btScalar(0.0001))
{
vec.setValue(1,0,0);
} else
{
btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
vec *= rlen;
}
for (int i=0;i<m_numPoints;i++)
{
btVector3 vtx = getScaledPoint(i);
newDot = vec.dot(vtx);
if (newDot > maxDot)
{
maxDot = newDot;
supVec = vtx;
}
}
return supVec;
}
void btConvexPointCloudShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const
{
btScalar newDot;
//use 'w' component of supportVerticesOut?
{
for (int i=0;i<numVectors;i++)
{
supportVerticesOut[i][3] = btScalar(-1e30);
}
}
for (int i=0;i<m_numPoints;i++)
{
btVector3 vtx = getScaledPoint(i);
for (int j=0;j<numVectors;j++)
{
const btVector3& vec = vectors[j];
newDot = vec.dot(vtx);
if (newDot > supportVerticesOut[j][3])
{
//WARNING: don't swap next lines, the w component would get overwritten!
supportVerticesOut[j] = vtx;
supportVerticesOut[j][3] = newDot;
}
}
}
}
btVector3 btConvexPointCloudShape::localGetSupportingVertex(const btVector3& vec)const
{
btVector3 supVertex = localGetSupportingVertexWithoutMargin(vec);
if ( getMargin()!=btScalar(0.) )
{
btVector3 vecnorm = vec;
if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON))
{
vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.));
}
vecnorm.normalize();
supVertex+= getMargin() * vecnorm;
}
return supVertex;
}
#endif
//currently just for debugging (drawing), perhaps future support for algebraic continuous collision detection
//Please note that you can debug-draw btConvexHullShape with the Raytracer Demo
int btConvexPointCloudShape::getNumVertices() const
{
return m_numPoints;
}
int btConvexPointCloudShape::getNumEdges() const
{
return 0;
}
void btConvexPointCloudShape::getEdge(int i,btVector3& pa,btVector3& pb) const
{
btAssert (0);
}
void btConvexPointCloudShape::getVertex(int i,btVector3& vtx) const
{
vtx = m_unscaledPoints[i]*m_localScaling;
}
int btConvexPointCloudShape::getNumPlanes() const
{
return 0;
}
void btConvexPointCloudShape::getPlane(btVector3& ,btVector3& ,int ) const
{
btAssert(0);
}
//not yet
bool btConvexPointCloudShape::isInside(const btVector3& ,btScalar ) const
{
btAssert(0);
return false;
}
| [
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
] | [
[
[
1,
156
]
]
] |
7c88b66345d92a76326af1883412628375822740 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/HEATXCH1/CONTCTHT.CPP | a961c4e686b17ff81c9b1b3b7537f0c766bbc2f4 | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,058 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
// SysCAD Copyright Kenwalt (Pty) Ltd 1992 - 1996
#include "stdafx.h"
#include "sc_defs.h"
#define __CONTCTHT_CPP
#include "contctht.h"
//#include "optoff.h"
#define WithPressureOption 0
//==========================================================================
/*#D:#T:Direct Contact Heater(1)
#X:#h<General Description>#n
The steam injection heater is a direct contact heater.
The unit has separate liquor and steam inlets, a hot liquor and a steam outlet.
#nThe model mixes the inlet streams, carries out any chemical reactions specified
by the user before calculating the amount of steam which must condense to obtain
the required temperature. The hot liquor and the excess steam exit at the equilibrium
pressure of the unit.
#nIf there is insufficient steam to obtain the required temperature, all of the
available steam is condensed.
#nIf the direct contact heater is inserted as part of a flash train, then the unit will
calculate the amount of steam required to obtain the user defined temperature. In this
case, there will be no steam exiting from the excess steam line.
#n#n
#n#u<#l<#b<Inputs and Outputs>>>#n#w
Label Input/Output Minimum number Maximum number#n
liquor Input 1 10#n
steam Input 1 1#n
hot liquor Output 1 1#n
excess steam Output 1 1#n
#a
To function the direct contact heater must have all of the above streams connected.
#n#n#h<Variables to be supplied by the user>#n
#i<TempSpec>:The method of calculating the final temperature, Temperature Rise or
Final Temperature.#n
#i<FinalTRqd>:The required temperature of the exiting hot liquor.#n
#i<TRiseRqd>:The required temperature increase between the incoming liquor and the
exiting hot liquor.
#n#n#h<Variables calculated by the model>#n
#i<TRise>:The calculated Temperature Rise between the entering and exiting liquor
streams.#n
#i<FinalP>:The operating pressure in the unit.#n
#i<FinalT>:The temperature of the exiting streams.
#n#n#h<Assumptions & Limitations>#n
All the steam condenses when inserted as part of a flash train.
#n#n#h<Chemical Equations>#n
By default, no chemical reactions occur in the steam injector.
Chemical reactions can be specified in a reaction file.
#n#h<Heat Transfer>#n
Heat loss to atmosphere is specified and the model maintains a thermal balance.
#n#h<Other>#n
Default model prefix:SI#n
Short name:ContctHt#n
Model type:Unit#n
#G:Units
*/
//==========================================================================
const byte ioidSI_Liq = 0;
const byte ioidSI_Steam = 1;
const byte ioidSI_HotLiq = 2;
const byte ioidSI_ESteam = 3;
static IOAreaRec ContactHeaterIOAreaList[] =
{{"Liquor", "Liquor", ioidSI_Liq , LIO_In0 , nc_MLnk, 1, 10, IOGRP(1)|IOPipeEntry|IOChgFracHgt|IOChgAperture|IOApertureHoriz, 1.0f},
{"Steam", "Steam" , ioidSI_Steam, LIO_In1 , nc_MLnk, 1, 1, IOGRP(1)|IOPipeEntry|IOChgFracHgt|IOChgAperture, 0.5f},
{"Hot Liquor", "HotLiquor", ioidSI_HotLiq, LIO_Out0, nc_MLnk, 1, 1, IOGRP(1)|IOPipeEntry|IOChgFracHgt|IOChgAperture, 0.5f},
{"Excess Steam","ExcessSteam",ioidSI_ESteam, LIO_Out1, nc_MLnk, 0, 1, IOGRP(1)|IOPipeEntry|IOChgFracHgt|IOChgAperture, 0.98f},
SPILL2AREA,
VENT2AREA(-1),
{NULL}}; //This lists the areas of the model where links can be attached.
static double Drw_ContactHeater[] = { DD_Poly, -6,8.4, -6,-8.4, 6,-8.4, 6,8.4, -6,8.4,
DD_Arc3, -6,8.4, 0,12, 6,8.4,
DD_Arc3, -6,-8.4, 0,-12, 6,-8.4,
DD_TagPos, 0, -15.5,
DD_End };
/*static double Drw_ContactHeater[] ={DD_Poly, -5,10, -5,-5, 5,-5, 5,10, -5,10,
DD_Arc3, -5,10, 0,13, 5,10,
DD_Arc3, -5,-5, 0,-8, 5,-5,
DD_End };*/
//--------------------------------------------------------------------------
IMPLEMENT_MODELUNIT(ContactHeater, "ContctHt", "1", Drw_ContactHeater, "HeatTransfer", "SI", TOC_ALL|TOC_GRP_ENERGY|TOC_HEATBAL,
// "HX - Direct Contact Heater(1)",
"Heat Transfer:Direct Contact Heater(1)",
"The direct contact heater model mixes the inlet streams, condenses "
"all the steam and carries out any chemical reactions specified before "
"rejecting the amount of heat lost and calculating the temperature, "
"composition and flow rate of the exit stream." )
//static MInitialiseTest InitTest(&ContactHeaterClass);
//SPECIEBLK_L(InitTest, H2OLiq, "H2O(l)", true);
//SPECIEBLK_V(InitTest, H2OVap, "H2O(g)", true);
ContactHeater::ContactHeater(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach) :
MN_Surge(pClass_, TagIn, pAttach, eAttach),
m_FTC(this)
{
AttachIOAreas(ContactHeaterIOAreaList, &PipeEntryGroup);
Contents.SetClosed(False);
iRqdCalcMode = QST_Free;
iTempSpec = QST_TRise;
dFinalTRqd = C_2_K(220.0);
dFinalPRqd = 2000.0;
dTRiseRqd = 10.0;
dTRise = 0.0;
dFinalP = Std_P;
dFinalT = Std_T;
dSatPOut = Std_P;
dVentRqd = 0.0;
dQmVapVent = 0.0;
SteamRqd = dNAN;
dPrevPress = dNAN;
//xx dVapFracRqd = dNAN;
iCalcMode = QST_General;
m_bShowQFeed = 0;
bTrackSteamStatus = 1;
bRemoveExcessVapour = 1;
bVentConnected = 0;
SetAllowedModes(true, NM_All|SM_Direct/*|SM_Inline*/|SM_Buffered|HM_All);
//m_EHX.Open(&CEHX_LossPerQmClass);
m_VLE.Open(NULL, true);
RegisterMacroMdlNode(CMMFlashTrain::MMIOs, &typeid(ContactHeater), ioidSI_Steam, mmio_MODEL, &typeid(CFT_Condenser));
}
//--------------------------------------------------------------------------
ContactHeater::~ContactHeater()
{
}
//--------------------------------------------------------------------------
void ContactHeater::BuildDataDefn(DataDefnBlk & DDB)
{
DDB.BeginStruct(this);
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
BuildDataDefnElevation(DDB);
if (SolveSurgeMethod())
{
DDB.Visibility(NM_Dynamic|SM_DynBoth|HM_All);
DDB.Double ("Pressure", "P", DC_P, "kPag", xidPMean, this, isResult|0);
DDB.Double ("Temperature", "T", DC_T, "C", xidTemp, this, isResult|0);
DDB.Double ("Density", "Rho", DC_Rho, "kg/m^3", xidRho, this, isResult|0);
DDB.Double ("Level", "Lvl", DC_Frac, "%", xidLevel, this, isResult|0);
DDB.Double ("Mass_Accum", "QmAcc", DC_Qm, "kg/s", &m_QmAcc, this, isResult|0);
DDB.Double ("Vol_Accum", "QvAcc", DC_Qv, "L/s", &m_QvAcc, this, isResult|0);
}
DDB.Visibility();
static DDBValueLst DDB0[]={
{QST_Free, "Free"},
{QST_ForceDemand, "Steam Demand"},
{QST_ForceGeneral, "Stand Alone"},
{0}};
static DDBValueLst DDB1[]={
{QST_TRise, "Temp Rise"},
{QST_FinalT, "Final Temp"},
#if WithPressureOption
{QST_FinalP, "Final Pressure"},
#endif
{0}};
static DDBValueLst DDB2[]={
{QST_FTCActive, "Flash Train"},
{QST_Makup, "Steam Makeup"},
{QST_General, "General"},
{0}};
DDB.Text ("");
DDB.Text ("Requirements");
DDB.Byte ("RqdCalcMode", "", DC_, "", &iRqdCalcMode, this, isParm|AffectsStruct, DDB0);
DDB.Byte ("TempSpec", "", DC_, "", &iTempSpec, this, isParm|AffectsStruct, DDB1);
DDB.Visibility(NSHM_All, (iTempSpec == QST_FinalT));
DDB.Double ("FinalTRqd", "", DC_T, "C", &dFinalTRqd, this, isParm);
DDB.Visibility(NSHM_All, (iTempSpec == QST_FinalP));
DDB.Double ("FinalPRqd", "", DC_P, "kPag", &dFinalPRqd, this, isParm);
DDB.Visibility(NSHM_All, (iTempSpec == QST_TRise));
DDB.Double ("TRiseRqd", "", DC_dT, "C", &dTRiseRqd, this, isParm);
DDB.Visibility();
DDB.Double ("SteamVentRqd", "", DC_Qm, "kg/s", &dVentRqd, this, isParm);
m_RB.Add_OnOff(DDB);
m_EHX.Add_OnOff(DDB);
DDB.Visibility(NM_Probal|SM_All|HM_All);
DDB.CheckBox("ShowQFeed", "", DC_, "", &m_bShowQFeed, this, isParm|SetOnChange);
DDB.Visibility(NM_Probal|SM_All|HM_All, !bVentConnected);
DDB.CheckBox("VentExcessVapour", "", DC_, "", &bRemoveExcessVapour,this, isParm|SetOnChange);
DDB.Visibility();
DDB.CheckBox("TrackSteamFd", "", DC_, "", &bTrackSteamStatus, this, isParm|SetOnChange);
DDB.Visibility();
DDB.Text ("Results");
DDB.Double ("TRise", "", DC_dT, "C", &dTRise, this, isResult|0);
DDB.Double ("FinalP", "", DC_P, "kPag", &dFinalP, this, isResult|NAN_OK);
DDB.Double ("FinalT", "", DC_T, "C", &dFinalT, this, isResult|NAN_OK);
DDB.Double ("SatP", "", DC_P, "kPag", &dSatPOut, this, isResult|noFile|noSnap|InitHidden);
DDB.Visibility(NM_Probal|SM_All|HM_All);
DDB.Double ("VapQmOut", "", DC_Qm, "kg/s", &dQmVapVent, this, isResult|noFile|noSnap|InitHidden);
DDB.Byte ("CalcMode", "", DC_, "", &iCalcMode, this, isResult/*|InitHidden*/, DDB2);
DDB.Visibility();
DDB.Double ("PrevP", "", DC_P, "kPa", &dPrevPress, this, isResult|noView);
//xx DDB.Double ("PrevVapFrac", "", DC_Frac, "", &dVapFracRqd, this, isResult|noView);
DDB.Text ("");
//NB: during a project load or save m_FTC.Active() is ALWAYS false!!!
//dword VFlags=m_FTC.Active() ? 0 : noView|noFile|noSnap;
m_FTC.BuildDataDefn(DDB);
//dword VFlags=m_FTC.Active() ? 0 : noView;
//DDB.Double ("QRqd", "", DC_Qm, "kg/s", &m_FTC.dQRqd, this, isResult|VFlags);
//DDB.Double ("QCond", "", DC_Qm, "kg/s", &m_FTC.dQCond, this, isResult|VFlags);
//DDB.Double ("SuctionP", "", DC_P, "kPa", &m_FTC.dSuctionP, this, isResult|noView|VFlags);
//DDB.Double ("MinSatPress", "", DC_P, "kPa", &m_FTC.dMinSatPress, this, isResult|VFlags);
//if (m_FTC.Active())
// {
// DDB.String ("FlashTrain", "", DC_, "", &m_FTC.pMNd->TagRef(), this, isResult|noFile|noSnap|VFlags);
// DDB.String ("FlashTrainEqp", "", DC_, "", m_FTC.MMList(), this, isResult|MultiLineStr|noFile|noSnap|VFlags);
// DDB.Text ("");
// }
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
AddMdlClosed(DDB);
AddMdlNetworked(DDB);
DDB.Visibility();
DDB.Text ("");
BuildDataDefnShowIOs(DDB);
if (SolveBufferedMethod())
BuildDataDefnIOOpts(DDB);
m_RB.BuildDataDefn(DDB);
m_EHX.BuildDataDefn(DDB);
if (m_bShowQFeed && NetProbalMethod())
DDB.Object(&m_QFeed, this, NULL, NULL, DDB_RqdPage);
if (SolveBufferedMethod())
{
DDB.Object(&Contents, this, NULL, NULL, DDB_RqdPage);
DDB.Object(&m_PresetImg, this, NULL, NULL, DDB_RqdPage);
}
DDB.EndStruct();
}
//--------------------------------------------------------------------------
flag ContactHeater::DataXchg(DataChangeBlk & DCB)
{
if (MN_Surge::DataXchg(DCB))
return 1;
if (m_FTC.DataXchg(DCB))
return 1;
switch (DCB.lHandle)
{
case xidClosed:
if (DCB.rB)
Contents.SetClosed(*DCB.rB, DCB.ForView());
DCB.B=Contents.Closed();
return 1;
}
return 0;
}
//---------------------------------------------------------------------------
flag ContactHeater::ValidateData(ValidateDataBlk & VDB)
{
flag OK=MN_Surge::ValidateData(VDB);
dTRiseRqd=ValidateRange(VDB, "TRiseRqd", 0.0, dTRiseRqd, 500.0);
dFinalTRqd=ValidateRange(VDB, "FinalTRqd", 20.0, dFinalTRqd, IF97_MaxSatT);
dFinalPRqd=ValidateRange(VDB, "FinalPRqd", 2.0, dFinalPRqd, IF97_MaxSatP);
return OK;
}
//--------------------------------------------------------------------------
void ContactHeater::EvalJoinPressures(long JoinMask)
{
if (NoFlwIOs()>0)
{
if (NetMethod()==NM_Probal || SolveMethod()!=SM_Buffered)
{
//if (!m_FTC.Active())
// m_FTC.SetSuctionP(IOP_Rmt(IOWithId_Self(ioidSI_HotLiq)));what does this do for us?
if (NoProcessJoins()>0)
{
//m_FTC.SetSuctionP(Min(dFinalP, MeasureJoinPressure(0)));
m_FTC.SetSuctionP(dFinalP);
// m_FTC.SetSuctionP(MeasureJoinPressure(0));
SetJoinPressure(0, m_FTC.SuctionP());
}
}
else
{
MdlNode::EvalJoinPressures(JoinMask);
}
}
}
//--------------------------------------------------------------------------
void ContactHeater::SetState(eScdMdlStateActs RqdState)
{
MN_Surge::SetState(RqdState);
switch (RqdState)
{
case MSA_PBInit:
m_FTC.SetState(RqdState);
break;
case MSA_ZeroFlows:
case MSA_Empty:
case MSA_PreSet:
break;
case MSA_SteadyState:
LogNote(FullObjTag(), 0, "SteadyState Undefined");
break;
}
}
//--------------------------------------------------------------------------
void ContactHeater::EvalJoinFlows(int JoinNo)
{
if (NoFlwIOs()>0)
switch (NetMethod())
{
case NM_Probal:
case NM_Dynamic:
break;
}
};
//--------------------------------------------------------------------------
class FinalTempFnd : public MRootFinderBase
{
public:
SpConduit &HL, &Liq, &Vp;
double LP,VentRqd;
double VQm;
ContactHeater &CH;
static CToleranceBlock s_Tol;
FinalTempFnd(SpConduit &HotLiquor, SpConduit &Vapour, SpConduit &Liquor, double LiquorP, double VentQmRqd, ContactHeater &ContactH);
double Function(double x);
};
CToleranceBlock FinalTempFnd::s_Tol(TBF_Both, "ContactHt:FinalTempFnd", 0.0, 1.0e-9);
//--------------------------------------------------------------------------
FinalTempFnd::FinalTempFnd(SpConduit &HotLiquor, SpConduit &Vapour, SpConduit &Liquor, double LiquorP, double VentQmRqd, ContactHeater &ContactH):
MRootFinderBase("Heater", s_Tol),//1e-9),
HL(HotLiquor),
Vp(Vapour),
Liq(Liquor),
CH(ContactH)
{
LP = LiquorP;
VentRqd = VentQmRqd;
VQm = Vp.QMass();
}
//--------------------------------------------------------------------------
double FinalTempFnd::Function(double x)
{
HL.QSetF(Liq, som_ALL, 1.0, LP);
HL.QAddM(Vp, som_ALL, Max(VQm, x));
CH.m_RB.EvalProducts(HL);
CH.m_EHX.EvalProducts(HL);
const double RqdFrac = (VentRqd>UsableMass ? VentRqd/GTZ(HL.VMass[CH.m_VLE.SatPVapIndex()/*H2OVap()*/]+HL.VMass[CH.m_VLE.SatPLiqIndex()/*H2OLiq()*/]) : 0.0);
const double f = Max(RqdFrac, 1.0-Min(1.0, x/GTZ(VQm)));
CH.m_VLE.SetSatPVapFrac(HL, f, 0);
double dFinalT = HL.Temp();
#ifndef _RELEASE
double P = HL.Press();
double SP = HL.SaturationP(dTarget);
#endif
return dFinalT;
}
//--------------------------------------------------------------------------
void ContactHeater::EvalProducts(CNodeEvalIndex & NEI)
{
if (NoFlwIOs()==0)
return;
switch (SolveMethod())
{
case SM_Direct:
{
dVentRqd = Max(0.0, dVentRqd);
const int IOSteam = IOWithId_Self(ioidSI_Steam);//Steam feed
const int IOESteam = IOWithId_Self(ioidSI_ESteam);//Excess Steam vent
const int IOLiqIn = IOWithId_Self(ioidSI_Liq);//Liquor feed
StkSpConduit Mixture("Mixture", chLINEID(), this);
StkSpConduit Liquor("Liquor", chLINEID(), this);
StkSpConduit Vapour("Vapour", chLINEID(), this);
SpConduit & HotLiquor = *(IOConduit(IOWithId_Self(ioidSI_HotLiq)));
double Pi = SigmaQInPMin(Mixture(), som_ALL, Id_2_Mask(ioidSI_Liq)|Id_2_Mask(ioidSI_Steam));
SigmaQInPMin(Liquor(), som_ALL, Id_2_Mask(ioidSI_Liq));
SigmaQInPMin(Vapour(), som_ALL, Id_2_Mask(ioidSI_Steam));
if (m_bShowQFeed)
m_QFeed.QCopy(Mixture());
bVentConnected = (IOESteam>=0);
const int si = m_VLE.SatPVapIndex()/*H2OVap()*/;
double LiquorQ = Liquor().QMass();
double LiquorQVap = Liquor().QMass(som_Gas); //vapour in liquor feed
//double LiquorP = Liquor().Press();//this is "WRONG" because of PMin used!
double LiquorT = Liquor().Temp();
double VentQ = (bVentConnected ? IOConduit(IOESteam)->QMass() : 0.0);
double VentSteamQ = (bVentConnected ? IOConduit(IOESteam)->VMass[si] : 0.0);
double VapourQ = Vapour().QMass();
double VapourQVap = Vapour().QMass(som_Gas);
double VapourSteamQ = Vapour().VMass[si];
//double VapourP = Vapour().Press();//this is "WRONG" because of PMin used!
//double VapourT = Vapour().Temp();//this is "WRONG" because of PMin used!
ASSERT(IOSteam>=0);
SpConduit & QSteamIn = *IOConduit(IOSteam);
double VapourT = QSteamIn.Temp();
double VapourP = QSteamIn.Press();
SpConduit & QLiqIn = *IOConduit(IOLiqIn);
double LiquorP = QLiqIn.Press();
double LiquorT_ = QLiqIn.Temp();
//const flag HasSteam = (Vapour().Qm(si)>1.0e-6);
const flag HasSteam = (VapourQ>1.0e-6);
const flag HasFeed = (Mixture().QMass()>1.0e-6);
const flag HasLiquor = (LiquorQ>1.0e-6);
SetCI(2, HasLiquor && !HasSteam);
SetCI(5, bTrackSteamStatus && HasSteam && (VapourSteamQ/VapourQ)<0.9999); //expect 100% steam in steam line
dQmVapVent = 0.0;
double RqdProdTemp;
CFlange &StmFl=*IOFlange(IOSteam);
bool GeneralCalc = (iRqdCalcMode==QST_ForceGeneral);
if (iRqdCalcMode==QST_Free)
{
GeneralCalc = !(m_FTC.Active() || StmFl.IsMakeUpAvail());
}
const bool DemandErr = (!GeneralCalc && !m_FTC.Active() && !StmFl.IsMakeUpAvail());
SetCI(6, DemandErr);
if (DemandErr)
GeneralCalc = true; //Force general calc
if (!GeneralCalc)
{
iCalcMode = (byte)(m_FTC.Active() ? QST_FTCActive : QST_Makup);
SetCI(2, HasLiquor && (VapourSteamQ<1.0e-6));
m_FTC.m_dQCond = VapourQ;//VapourQVap;//VapourSteamQ
RqdProdTemp = (iTempSpec==QST_TRise) ? Min(LiquorT+dTRiseRqd, IF97_MaxSatT) : dFinalTRqd;
if (HasSteam || HasFeed)
{
double RqdTemp = RqdProdTemp;
// Assume m_FTC.m_dQRqd is approximately correct
m_FTC.m_dQRqd=Max(0.0, m_FTC.m_dQRqd);
// Required Temp cannot go higher than Steam Saturated Temperature
const double SatT = Vapour().SaturationT(VapourP);
const double RqdT = Range(ZeroCinK, RqdTemp, max(SatT, LiquorT)); //ensure the target temp is **reasonable**
const double LiqSatP = Liquor().SaturationP(RqdT);
const double VapSatP = Vapour().SaturationP(RqdT);
const double P_ = Vapour().SaturationP(LiquorT);
dFinalP = LiqSatP; //a "reasonable" guess
//dFinalP = Max(dFinalP, P_); //ensure the target pressure is **reasonable**
//dFinalP = Max(2.0/*LiquorP*//*dFinalP*/, P_); //ensure the target pressure is **reasonable**
double VentRqd = dVentRqd;//(bVentConnected ? dVentRqd : 0.0);
SetCI(4, RqdT<RqdTemp);
double EstFinalP = Valid(dPrevPress) ? Range(dFinalP-20.0, dPrevPress, dFinalP+20.0) : dFinalP;
//double EstFinalP = dFinalP;
FinalTempFnd FTF(Mixture(), Vapour(), Liquor(), EstFinalP, VentRqd, *this);
FTF.SetTarget(RqdT);
if (Valid(SteamRqd))
{
FTF.SetEstimate(SteamRqd, 1.0);
SteamRqd = dNAN;
}
flag Ok = false;
double MaxQStm=Max(1.1*(LiquorQ+VapourQ-VentQ), 0.1);
int iRet=FTF.Start(0.0, MaxQStm);
if (iRet==RF_EstimateOK) //estimate is good, solve not required
{
SteamRqd = FTF.Result();
Ok = true;
}
else
{
if (iRet==RF_BadEstimate)
iRet = FTF.Start(0.0, MaxQStm); // Restart
if (iRet==RF_OK)
if (FTF.Solve_Brent()==RF_OK)
{
SteamRqd = FTF.Result();
Ok = true;
}
}
if (Ok)
{//now call function with ACTUAL VQm
//doing this causes BIG stability errors, in some cases (eg Nickel demo project)...
//double T = FTF.Function(VapourQ);
dFinalP = Mixture().Press(); //determine ACTUAL finalP
}
double ExtraVapourQ = Mixture().QMass(som_Gas);
//m_FTC.dQCond = Max(0.0, VapourQ+LiquorQVap-ExtraVapourQ); //assumes no vapour consumed/generated in RB !!!
if (Ok)
{//If required, adjust SteamRqd to get correct steam vent...
//double ExcessVap = Mixture().QMass(som_Gas);
const double exsteam = Mixture().VMass[si];
const double diff = exsteam-VentRqd;
if (diff>1.0e-12)
{
if (iCalcMode==QST_Makup)
SteamRqd = Max(SteamRqd - (diff * 0.95), 0.0);
else
SteamRqd = Max(SteamRqd - (diff * 0.80), 0.0);
}
m_FTC.m_dQRqd = SteamRqd;
}
else
{
// if a problem just add
m_FTC.m_dQRqd = 0.1;
}
//TODO TODO: Improve Contact Heater convergance...
//1) Fix for bad mass balance after first solved!")
// eg change SteamVentRequired significantly, then press solve, solves with balance error
// (ie m_FTC.dQRqd delay/missmatch!?!?!) is OK after pressing solve again!
//2) Perhaps should be "loop within loop" to meet temperature and vent requirement efeciently?!?
//=========================================================
#if dbgModels
if (dbgFlashTrain())
dbgpln("BC: Est:%10.4f MxFl:%10.4f", m_FTC.dQRqd, QRqdEst);
#endif
}
else
{//no steam suplied
dFinalP=LiquorP;
m_FTC.m_dQRqd=0.0;
Mixture().QSetF(Liquor(), som_ALL, 1.0, dFinalP);
}
m_FTC.m_dQRqd=Max(0.0, m_FTC.m_dQRqd);
// Mixture now flashed
//if (!m_FTC.Active())
StmFl.SetMakeUpReqd(m_FTC.m_dQRqd);
dQmVapVent = Mixture().QMass(som_Gas);
if (bVentConnected)
{
HotLiquor.QSetF(Mixture(), som_SL, 1.0, dFinalP);
SpConduit& ESteam = *(IOConduit(IOESteam));
ESteam.QSetF(Mixture(), som_Gas, 1.0, dFinalP);
ClrCI(3);
}
else
{
//Where should Excess Steam go?
if (m_FTC.Active())
HotLiquor.QSetF(Mixture(), som_SL, 1.0, dFinalP); //throw excess steam (and vapours) away
else
HotLiquor.QSetF(Mixture(), bRemoveExcessVapour ? som_SL : som_ALL, 1.0, dFinalP);
if (dVentRqd>0.0)
SetCI(3, true);
else if (!m_FTC.Active())
SetCI(3, m_FTC.m_dQRqd<0.999999*VapourQ);
}
}
else
{
iCalcMode = QST_General;
//SetCI(2, (Mixture().Qm(si)<1.0e-6));???
m_RB.EvalProducts(Mixture());
m_EHX.EvalProducts(Mixture());
double TPress = LiquorP;
RqdProdTemp = (iTempSpec==QST_TRise) ? LiquorT+dTRiseRqd : dFinalTRqd;
if (HasSteam)
{
double RqdTemp = RqdProdTemp;
TPress = Mixture().SaturationP(RqdTemp);
m_VLE.PFlash(Mixture(), TPress, 0.0, 0);
double Tmp = Mixture().Temp();
TPress = Mixture().SaturationP(RqdTemp); //new SaturationP after Flash
double exsteam = Mixture().VMass[si];
if (Tmp > RqdTemp || exsteam > MeasTolerance) // If there is enough steam, find the equilibrium
{
double RqdPure = Mixture().PureSaturationP(RqdTemp);
//TPress should be less than RqdPure, if not then probably an error in SaturationP at RqdTemp for current specie model
ASSERT(TPress<=RqdPure); //something may be wrong...
//TPress = (TPress + RqdPure)/2.0; //guess
if (Valid(dPrevPress))
TPress = Range(TPress-20.0, dPrevPress, RqdPure); //use previous value?
const int MxIter=20;
for (int iIter=0; iIter<MxIter; iIter++)
{
m_VLE.PFlash(Mixture(), TPress, 0.0, 0);
Tmp = Mixture().Temp();
double TmpDiff = RqdTemp - Tmp;
if (fabs(TmpDiff) < 1.0e-5)
{
TPress = Mixture().SaturationP(RqdTemp);
iIter = MxIter;
}
else
{
exsteam = Mixture().VMass[si];
if (Tmp > RqdTemp || exsteam > MeasTolerance)
{//try again...
TPress = Mixture().SaturationP(RqdTemp);
//TPress -= (TPress * 1.0e-5); //reduce pressure to converge faster???
TPress += TmpDiff; //reduce pressure to converge faster???
}
else
{//no more steam left to condense to increase temperature...
TPress = Mixture().SaturationP(Tmp);
iIter = MxIter;
}
}
}
}
}
double exvap = Mixture().QMass(som_Gas);
HotLiquor.QSetF(Mixture(), som_SL, 1.0, TPress);
dQmVapVent = Mixture().QMass(som_Gas);
if (bVentConnected)
{
ClrCI(3);
SpConduit & ESteam = *(IOConduit(IOESteam));
ESteam.QSetF(Mixture(), som_Gas, 1.0, TPress);
}
else
{
SetCI(3, fabs(exvap)>UsableMass);
if (!bRemoveExcessVapour)
HotLiquor.QAddF(Mixture(), som_Gas, 1.0);
}
}
dFinalT = HotLiquor.Temp();
dFinalP = HotLiquor.Press();//HotLiquor.SaturationP(dFinalT);
dSatPOut = HotLiquor.SaturationP(dFinalT);
dPrevPress = dSatPOut;
dTRise = dFinalT - LiquorT;
SetCI(1, HasLiquor && !GeneralCalc && fabs(dFinalT-RqdProdTemp)/RqdProdTemp>1.0e-4);
m_FTC.m_dMinSatPress = 1.0; // ToFix
}
break;
default:
MN_Surge::EvalProducts(NEI);
}
}
//--------------------------------------------------------------------------
flag ContactHeater::CIStrng(int No, pchar & pS)
{
// NB check CBCount is large enough.
switch (No-CBContext())
{
case 1: pS="W\tCannot Achieve Temperature Requirements"; return 1;
case 2: pS="W\tNo Steam Supplied"; return 1;
case 3: pS="W\tNo Vent Defined"; return 1;
case 4: pS="W\tTemperature Required too high based on feed streams"; return 1;
case 5: pS="W\tExpect pure steam in steam line"; return 1;
case 6: pS="W\tExpect flash-train or makeup steam line arrangement"; return 1;
default:
return MN_Surge::CIStrng(No, pS);
}
}
//==========================================================================
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
9
],
[
11,
11
],
[
14,
73
],
[
80,
82
],
[
88,
102
],
[
106,
113
],
[
115,
116
],
[
118,
128
],
[
130,
133
],
[
138,
153
],
[
155,
155
],
[
166,
168
],
[
174,
175
],
[
179,
179
],
[
197,
197
],
[
203,
212
],
[
214,
214
],
[
216,
237
],
[
239,
244
],
[
247,
247
],
[
250,
250
],
[
253,
253
],
[
255,
268
],
[
271,
289
],
[
291,
298
],
[
301,
301
],
[
305,
305
],
[
310,
311
],
[
317,
320
],
[
322,
343
],
[
345,
345
],
[
348,
388
],
[
392,
392
],
[
394,
403
],
[
405,
407
],
[
409,
409
],
[
411,
426
],
[
429,
430
],
[
432,
450
],
[
455,
461
],
[
473,
474
],
[
476,
606
],
[
609,
617
],
[
619,
633
],
[
635,
684
],
[
686,
690
],
[
692,
706
],
[
708,
714
]
],
[
[
10,
10
],
[
12,
13
],
[
83,
87
],
[
114,
114
],
[
117,
117
],
[
134,
135
],
[
156,
165
],
[
169,
173
],
[
176,
178
],
[
180,
189
],
[
191,
191
],
[
193,
193
],
[
195,
196
],
[
215,
215
],
[
245,
246
],
[
254,
254
],
[
290,
290
],
[
299,
300
],
[
302,
304
],
[
306,
307
],
[
309,
309
],
[
312,
316
],
[
321,
321
],
[
451,
454
],
[
462,
472
],
[
475,
475
],
[
685,
685
],
[
707,
707
]
],
[
[
74,
79
],
[
103,
105
],
[
129,
129
],
[
136,
137
],
[
154,
154
],
[
190,
190
],
[
192,
192
],
[
194,
194
],
[
198,
202
],
[
213,
213
],
[
238,
238
],
[
248,
249
],
[
251,
252
],
[
269,
270
],
[
308,
308
],
[
344,
344
],
[
346,
347
],
[
389,
391
],
[
393,
393
],
[
404,
404
],
[
408,
408
],
[
410,
410
],
[
427,
428
],
[
431,
431
],
[
607,
608
],
[
618,
618
],
[
634,
634
],
[
691,
691
]
]
] |
0c7cdc5c5e614f26a440626b3e0377b624d30338 | aaf23f851e5c0ae43eb60c2d1a9f05462d7b964c | /src/huawei_a1/src/interface.cpp | a9596e184cf19d7a3a7106b2f35668acd72e3823 | [] | no_license | ismailwissam/bill-parser | 28ccb68857cb7d6be04207534e7250da82b5c55f | 5e195d606fcbbb1f69cbe148dde2413450d381fb | refs/heads/master | 2021-01-10T10:25:20.175318 | 2010-09-20T02:20:37 | 2010-09-20T02:20:37 | 50,747,248 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,363 | cpp | #include "interface.hpp"
#include "module_base.hpp"
#include <map>
/*!
* 话单模块指针
*/
extern std::auto_ptr<BillModule> glb_BillModulePtr;
/*!
* 多线程初始化
*/
int InitMT()
{
BillModule* loc_NewMod = glb_BillModulePtr->billmodClone();
return reinterpret_cast<int>(loc_NewMod);
}
/*!
* 多线程释放
*/
void UninitMT(int handle)
{
BillModule* loc_Mod = reinterpret_cast<BillModule*>(handle);
delete loc_Mod;
}
/*!
* 返回话单类型
*/
const char* GetTypeName(int type_idx)
{
return glb_BillModulePtr->billmodGetTypeName(type_idx);
}
/*!
* 返回话单类型的每项字段类型
*/
const char* GetItemName(int type_idx, int item_idx)
{
return glb_BillModulePtr->billmodGetItemName(type_idx, item_idx);
}
/*!
* 解析话单入口(单线程版本不允许同时解析两个话单文件)
*/
bool ParseFile(const char* file_name)
{
return glb_BillModulePtr->billmodParseFile(file_name);
}
bool ParseFileMT(int handle, const char* file_name)
{
BillModule* loc_Mod = reinterpret_cast<BillModule*>(handle);
return loc_Mod->billmodParseFile(file_name);
}
/*!
* 获取下一条话单内容
*/
bool FetchNextBill()
{
return glb_BillModulePtr->billmodFetchNextBill();
}
bool FetchNextBillMT(int handle)
{
BillModule* loc_Mod = reinterpret_cast<BillModule*>(handle);
return loc_Mod->billmodFetchNextBill();
}
/*!
* 当前解析出的话单类型
*/
int CurBillType()
{
return glb_BillModulePtr->billmodCurBillType();
}
int CurBillTypeMT(int handle)
{
BillModule* loc_Mod = reinterpret_cast<BillModule*>(handle);
return loc_Mod->billmodCurBillType();
}
/*!
* 当前解析出的话单类型
*/
const char* CurBillName()
{
return glb_BillModulePtr->billmodCurBillName();
}
const char* CurBillNameMT(int handle)
{
BillModule* loc_Mod = reinterpret_cast<BillModule*>(handle);
return loc_Mod->billmodCurBillName();
}
/*!
* 获得话单某项内容
*/
const char* GetItemData(const char* item_name)
{
return glb_BillModulePtr->billmodGetItemData(item_name);
}
const char* GetItemDataMT(int handle, const char* item_name)
{
BillModule* loc_Mod = reinterpret_cast<BillModule*>(handle);
return loc_Mod->billmodGetItemData(item_name);
}
| [
"ewangplay@81b94f52-7618-9c36-a7be-76e94dd6e0e6"
] | [
[
[
1,
109
]
]
] |
c5802e0a52cc48ba6fab62473ce165185e7388a2 | e5ded38277ec6db30ef7721a9f6f5757924e130e | /Cpp/SoSe10/Blatt06.Aufgabe02/stdafx.cpp | 73c25db5b96e62a741a87d94bd5d34b01dc74c78 | [] | no_license | TetsuoCologne/sose10 | 67986c8a014c4bdef19dc52e0e71e91602600aa0 | 67505537b0eec497d474bd2d28621e36e8858307 | refs/heads/master | 2020-05-27T04:36:02.620546 | 2010-06-22T20:47:08 | 2010-06-22T20:47:08 | 32,480,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Blatt06.Aufgabe02.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]@f2f8bf26-27bb-74d3-be08-1e18597623ec"
] | [
[
[
1,
8
]
]
] |
5634a24ddb5ecf1be4a0d9662a84acb40af2daf3 | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_代码统计专用文件夹/C++Primer中文版(第4版)/第五章 表达式/20090122_测试5.11_new和delete表达式_4撤销动态创建的数组.cpp | 93a010ec92d665a0576d3e50c28f27a68e61b697 | [] | no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 231 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
int *pi=&i;
string str="dwarves";
double *pd=new double(33);
delete str; //error
delete pi; //error
delete pd; //ok
return 0;
} | [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
16
]
]
] |
17ba9ea09e1633d35e94decc5bbd58c36cc0e0dc | 85e50a5e068a800973d57be93d8edc15a580325d | /ProgressDialog.h | 05698479f493fa389f170f841201506f665ba1ec | [] | no_license | jjzhang166/markessien-p2p. | 9715a2b05bd129bce4798d2ad8b8d51684c05543 | a691f47fc198f76f7fd5e66cdab1be7f39c0fbf1 | refs/heads/master | 2021-08-12T01:36:01.851011 | 2010-10-23T12:26:52 | 2010-10-23T12:26:52 | 110,662,175 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,347 | h | // ProgressDialog.h : Declaration of the CProgressDialog
#ifndef __PROGRESSDIALOG_H_
#define __PROGRESSDIALOG_H_
#include "resource.h" // main symbols
#include <atlhost.h>
/////////////////////////////////////////////////////////////////////////////
// CProgressDialog
class CProgressDialog :
public CAxDialogImpl<CProgressDialog>
{
public:
CProgressDialog()
{
}
~CProgressDialog()
{
}
enum { IDD = IDD_PROGRESSDIALOG };
BEGIN_MSG_MAP(CProgressDialog)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_ID_HANDLER(IDOK, OnOK)
COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
END_MSG_MAP()
// Handler prototypes:
// LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
// LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
// LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);
void UpdateProgress(LPCTSTR psz);
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 1; // Let the system set the focus
}
LRESULT OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
EndDialog(wID);
return 0;
}
LRESULT OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
EndDialog(wID);
return 0;
}
};
#endif //__PROGRESSDIALOG_H_
| [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
90b78d397e7668916bcea02fff366777fc1d51dc | 28866d979b8649440ba0e48274917b87b23321f4 | /notebook/src/splay_trees/orgsplay.cpp | 17edf30ccc9637d30f85a131511011c1a83b36e1 | [] | no_license | sravi4701/cat-us-trophy | 45237e50e46325ab02842da779707efa3c01690f | f60152fca341970b1593c538939cbfeb4152e1dc | refs/heads/master | 2021-01-16T23:07:05.632872 | 2011-01-12T19:24:19 | 2011-01-12T19:24:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,103 | cpp |
#include <cstdio>
#define max(a,b) ((a)>(b)?(a):(b))
struct Tsplay
{
#define Lch(x) T[x].l
#define Rch(x) T[x].r
#define Par(x) T[x].p
#define Val(x) T[x].val
#define Sum(x) T[x].sum
#define Lms(x) T[x].lms
#define Rms(x) T[x].rms
#define Ms(x) T[x].ms
#define Size(x) T[x].size
int l,r,p,size;
int sum,ms,lms,rms,val;
} T[200005];
int N,Que,root,tot,cnt,x,y;
char cmd[105];
inline void Tupdate(int x)
{
Size(x)=Size(Lch(x))+1+Size(Rch(x));
Sum(x)=Sum(Lch(x))+Val(x)+Sum(Rch(x));
Lms(x)=max(Lms(Lch(x)),Sum(Lch(x))+Val(x)+Lms(Rch(x)));
Rms(x)=max(Rms(Rch(x)),Rms(Lch(x))+Val(x)+Sum(Rch(x)));
Ms(x)=Rms(Lch(x))+Val(x)+Lms(Rch(x));
if (Lch(x)) Ms(x)=max(Ms(x),Ms(Lch(x)));
if (Rch(x)) Ms(x)=max(Ms(x),Ms(Rch(x)));
}
inline void zig(int x)
{
int y=Par(x),z=Par(y);
Lch(y)=Rch(x),Par(Lch(y))=Rch(x)=y;
if (Lch(z)==y) Lch(z)=x;
else Rch(z)=x;
Par(x)=z,Par(y)=x;
Tupdate(y);
}
inline void zag(int x)
{
int y=Par(x),z=Par(y);
Rch(y)=Lch(x),Par(Rch(y))=Lch(x)=y;
if (Lch(z)==y) Lch(z)=x;
else Rch(z)=x;
Par(x)=z,Par(y)=x;
Tupdate(y);
}
inline void splay(int &root,int x)
{
for (int y,z;Par(x);)
{
y=Par(x),z=Par(y);
if (!z)
if (Lch(y)==x) zig(x);
else zag(x);
else
if (Lch(z)==y)
if (Lch(y)==x) zig(y),zig(x);
else zag(x),zig(x);
else
if (Rch(y)==x) zag(y),zag(x);
else zig(x),zag(x);
}
Tupdate(root=x);
}
inline int Findkth(int root,int k)
{
for (int p=root;;)
if (k<=Size(Lch(p))) p=Lch(p);
else
if (k<=Size(Lch(p))+1) return p;
else k-=Size(Lch(p))+1,p=Rch(p);
}
inline int Tjoin(int u,int v)
{
if (!u) return v;
if (!v) return u;
int p=u;
for (;Rch(p);p=Rch(p));
splay(u,p);
return Rch(p)=v,Par(v)=p,p;
}
inline void D(int x)
{
splay(root,x);
Par(Lch(x))=Par(Rch(x))=0;
root=Tjoin(Lch(x),Rch(x));
Tupdate(root);
}
inline void I(int x,int y)
{
splay(root,x);
int v=Lch(x);
for (;Rch(v);v=Rch(v));
Rch(v)=++tot,Par(tot)=v,Size(tot)=1;
Sum(tot)=Ms(tot)=Lms(tot)=Rms(tot)=Val(tot)=y;
splay(root,tot);
}
inline void R(int x,int y)
{
Val(x)=y;
splay(root,x);
}
inline void Q(int x,int y)
{
splay(root,y);
Par(Lch(y))=0;
splay(Lch(y),x);
Par(x)=y;
printf("%d\n",Ms(Rch(x)));
}
void print_r(int node)
{
if(!node) { printf("()"); return; }
printf("(");
print_r( Lch(node) );
printf(" %d ",Val(node));
print_r( Rch(node) );
printf(")");
}
void print_l(int node)
{
if(!node) { printf("XX"); return; }
printf(" %d ",Val(node));
printf("(");
print_l( Lch(node) );
printf(",");
print_l( Rch(node) );
printf(")");
}
int main()
{
scanf("%d",&N);
for (int i=1;i<=N;++i)
{
scanf("%d",&Val(i));
Sum(i)=Ms(i)=Lms(i)=Rms(i)=Val(i);
Par(i)=i-1,Rch(i-1)=i,Size(i)=N-i+1;
splay(root,i);
}
splay(root,1),Par(N+1)=1,Lch(1)=N+1,Size(N+1)=1,splay(root,N+1);
splay(root,N),Par(N+2)=N,Rch(N)=N+2,Size(N+2)=1,splay(root,N+2);
tot=N+2;
for (scanf("%d",&Que);Que--;)
{
scanf("%s%d",cmd,&x);
if (cmd[0]=='D') D(Findkth(root,x+1));
else
{
scanf("%d",&y);
if (cmd[0]=='Q') Q(Findkth(root,x),Findkth(root,y+2));
else
if (cmd[0]=='I') I(Findkth(root,x+1),y);
else R(Findkth(root,x+1),y);
}
}
print_r(root); printf("\n");
print_l(root); printf("\n");
return 0;
}
//(((() 0 ((() 3 (() -4 (() 3 ()))) -1 ())) 6 ()) 0 ())
// 0 ( 6 ( 0 (XX, -1 ( 3 (XX, -4 (XX, 3 (XX,XX))),XX)),XX),XX)
//((() 0 ((() 3 ()) -1 (() 3 ((() -1 (() -4 ())) 2 ())))) 0 ())
// 0 ( 0 (XX, -1 ( 3 (XX,XX), 3 (XX, 2 ( -1 (XX, -4 (XX,XX)),XX)))),XX)
| [
"[email protected]"
] | [
[
[
1,
172
]
]
] |
5bc4f8257f4d1e3a294594b2e9a11f59fc6fa650 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_void_returns_fail.cpp | af380d1df55ce02ad24228f378b229f3b02eae61 | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | cpp |
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_NO_VOID_RETURNS
// This file should not compile, if it does then
// BOOST_NO_VOID_RETURNS need not be defined.
// see boost_no_void_returns.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_no_void_returns.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifdef BOOST_NO_VOID_RETURNS
#include "boost_no_void_returns.ipp"
#else
#error "this file should not compile"
#endif
int main( int, char *[] )
{
return boost_no_void_returns::test();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
39
]
]
] |
4b1dd8e3538810a02dcfd36c71e028ce93c34f2b | 0c1f669f3dfdab47085bf537348b0354f836abea | / qtremotedroid/SmartScaner/SmartScaner/SmartScanerDlg.cpp | 85f144dc51efa18fef04a4206a6dbc174a382e9c | [] | no_license | harlentan/qtremotedroid | fc5fc96d4374c39561aea73470a88d1f0a68b637 | d07dd045213711538b38c7ced2fd6d5a8edcf241 | refs/heads/master | 2021-01-10T11:37:59.331004 | 2010-12-12T09:55:39 | 2010-12-12T09:55:39 | 54,114,402 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,988 | cpp | // SmartScanerDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "SmartScaner.h"
#include "SmartScanerDlg.h"
#include "devguid.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//dispString = new String;
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CSmartScanerDlg 对话框
CSmartScanerDlg::CSmartScanerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSmartScanerDlg::IDD, pParent)
, strEdit(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CSmartScanerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_SCAN, conEdit);
DDX_Text(pDX, IDC_EDIT_SCAN, strEdit);
DDX_Control(pDX, IDC_EDIT_RTS, conRTS);
}
BEGIN_MESSAGE_MAP(CSmartScanerDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON_SCAN, &CSmartScanerDlg::OnBnClickedButtonScan)
END_MESSAGE_MAP()
// CSmartScanerDlg 消息处理程序
BOOL CSmartScanerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CSmartScanerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CSmartScanerDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标显示。
//
HCURSOR CSmartScanerDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
// Scan and display the COM port information
HRESULT CSmartScanerDlg::Scan(void)
{
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i;
hDevInfo = SetupDiGetClassDevs((LPGUID) &GUID_DEVCLASS_PORTS, 0, 0,DIGCF_PRESENT);
/*
GUID_DEVCLASS_FDC 软盘控制器
GUID_DEVCLASS_DISPLAY 显示卡
GUID_DEVCLASS_CDROM 光驱
GUID_DEVCLASS_KEYBOARD 键盘
GUID_DEVCLASS_COMPUTER 计算机
GUID_DEVCLASS_SYSTEM 系统
GUID_DEVCLASS_DISKDRIVE 磁盘驱动器
GUID_DEVCLASS_MEDIA 声音、视频和游戏控制器
GUID_DEVCLASS_MODEM MODEM
GUID_DEVCLASS_MOUSE 鼠标和其他指针设备
GUID_DEVCLASS_NET 网络设备器
GUID_DEVCLASS_USB 通用串行总线控制器
GUID_DEVCLASS_FLOPPYDISK 软盘驱动器
GUID_DEVCLASS_UNKNOWN 未知设备
GUID_DEVCLASS_SCSIADAPTER SCSI 和 RAID 控制器
GUID_DEVCLASS_HDC IDE ATA/ATAPI 控制器
GUID_DEVCLASS_PORTS 端口(COM 和 LPT)
GUID_DEVCLASS_MONITOR 监视器
*/
if (hDevInfo == INVALID_HANDLE_VALUE)
{
// Insert error handling here.
return -1;
}
// Enumerate through all devices in Set.
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=0;SetupDiEnumDeviceInfo(hDevInfo,i,
&DeviceInfoData);i++)
{
DWORD DataT;
//LPTSTR buffer = NULL;
char buffer[2048];
DWORD buffersize =sizeof(buffer);
while (!SetupDiGetDeviceRegistryProperty(
hDevInfo,
&DeviceInfoData,
SPDRP_FRIENDLYNAME,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if (GetLastError() ==
ERROR_INSUFFICIENT_BUFFER)
{
// Change the buffer size.
//if (buffer) LocalFree(buffer);
//buffer = (PSP_INF_INFORMATION)LocalAlloc(LPTR,buffersize);
}
else
{
// Insert error handling here.
break;
}
}
printf("Result:[%s]\n",buffer);
disp.Append(CString(buffer));
//disp.Append
disp.Append(_T("\r\n"));
conEdit.SetWindowTextW(disp.GetString());
}
SetupDiDestroyDeviceInfoList(hDevInfo);
if (disp.GetString()){
MessageBox(_T("no device find"), _T("prompt"));
}
return E_NOTIMPL;
}
void CSmartScanerDlg::OnBnClickedButtonScan()
{
// TODO: 在此添加控件通知处理程序代码
Scan();
}
LRESULT CSmartScanerDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: 在此添加专用代码和/或调用基类
if(message == WM_DEVICECHANGE) //0x8000,0x8004
{
CString str;
DEV_BROADCAST_HDR* dhr = (DEV_BROADCAST_HDR *)lParam;
switch(wParam)
{
case DBT_CONFIGCHANGECANCELED:
TRACE( "DBT_CONFIGCHANGECANCELED ");
break;
case DBT_CONFIGCHANGED:
TRACE( "DBT_CONFIGCHANGED ");
break;
case DBT_DEVICEQUERYREMOVE:
TRACE( "DBT_DEVICEQUERYREMOVE ");
break;
case DBT_DEVICEQUERYREMOVEFAILED:
TRACE( "DBT_DEVICEQUERYREMOVEFAILED ");
break;
case DBT_DEVICEREMOVEPENDING:
TRACE( "DBT_DEVICEREMOVEPENDING ");
break;
case DBT_DEVICETYPESPECIFIC:
TRACE( "DBT_DEVICETYPESPECIFIC ");
break;
case DBT_QUERYCHANGECONFIG:
TRACE( "DBT_QUERYCHANGECONFIG ");
break;
case DBT_USERDEFINED:
TRACE( "DBT_USERDEFINED ");
break;
case DBT_DEVICEARRIVAL:
if(dhr-> dbch_devicetype == DBT_DEVTYP_PORT)
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)dhr;
if(lpdbv-> dbcv_flags & DBTF_MEDIA)
{
str.Format( "Drive %c 插入 ", FirstDriveFromMask(lpdbv -> dbcv_unitmask));
//AfxMessageBox(str);
}
else
{
char ch = FirstDriveFromMask(lpdbv -> dbcv_unitmask);
str.Format( "%c:\\ ",ch);
}
}
break;
case DBT_DEVICEREMOVECOMPLETE:
if(dhr-dbch_devicetype == DBT_DEVTYP_VOLUME)
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)dhr;
if(lpdbv-> dbcv_flags & DBTF_MEDIA)
{
str.Format( "Drive %c 拔除 ",FirstDriveFromMask(lpdbv -> dbcv_unitmask));
}
else
{
str.Format( "Drive %c 拔除 ",FirstDriveFromMask(lpdbv -> dbcv_unitmask));
}
//AfxMessageBox(str);
}
break;
default:
break;
}
}
return CDialog::WindowProc(message, wParam, lParam);
}
| [
"[email protected]"
] | [
[
[
1,
326
]
]
] |
9cd074f2fb5bc36895c48e0dec426696713df885 | b7cc41e4fe71b5846deac2c4961846d3dba922ab | /hud.h | 7bac715e6d8f86854cbb028ac18a8bfbe8381aea | [] | no_license | rwarrin/LudumDare19 | dd81680a0f209fac7d42174b11bc2f0a28090739 | ab04ec19e4fb86aa277c3d5abd7f7045a8bc688a | refs/heads/master | 2021-01-16T18:29:10.873439 | 2010-12-20T08:49:01 | 2010-12-20T08:49:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | h | #ifndef HUD_H
#define HUD_H
#include "Globals.h"
#include <hge.h>
#include <hgefont.h>
class HUD {
public:
HUD();
~HUD();
bool Render();
private:
hgeFont *font;
};
#endif // HUD_H | [
"[email protected]"
] | [
[
[
1,
19
]
]
] |
3608ccfac0300a29f0433529fbad824dbdf99b67 | c70941413b8f7bf90173533115c148411c868bad | /dev/unit_tests/src/UnitTestsApp.cpp | 30f70a5c94e3b49236b5012251cb0c65550215dc | [] | no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 941 | cpp | #include "vtxLogManager.h"
#include "vtxStringHelper.h"
#include "vtxtestsUnitTestHost.h"
#include "vtxtestsUnitTestList.h"
#include <conio.h>
using namespace vtx::tests;
int main(int argc, char** argv)
{
UnitTestHost host;
if(argc > 1)
{
const vtx::String test_name = argv[1];
RUN_TEST_FROM_STRING(host, test_name);
}
else
{
std::cout << "You haven't provided a test name as first parameter, choose a test manually..." << std::endl;
for(int i=0; i<STR_TEST_LIST_LEN; ++i)
std::cout << "[" << i << "] " << STR_TEST_LIST[i] << std::endl;
std::string choice;
std::getline(std::cin, choice);
int choice_int = vtx::StringHelper::toInt(choice);
if(choice_int < 0 || choice_int >= STR_TEST_LIST_LEN)
{
std::cout << "You have chosen an invalid test index !" << std::endl;
getch();
}
else
RUN_TEST_FROM_STRING(host, vtx::String(STR_TEST_LIST[choice_int]));
}
}
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
] | [
[
[
1,
39
]
]
] |
691898942bcd1790712aa085b147e7af7863fed3 | 0fb5a041afce1fd5b222b73e544c5ba0abd116eb | /trunk/Physics/RigidBody.cpp | e378d9ac2761316c420dda3bc8e422a445bd2bcf | [] | no_license | BackupTheBerlios/edge-svn | 83bfa5b66705a132f8a0232b489e05b996b2c82c | a26699e2877debe117a82c512641847c0c3d156e | refs/heads/master | 2020-12-12T21:00:56.142965 | 2005-09-04T12:19:36 | 2005-09-04T12:19:36 | 40,668,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,939 | cpp | #include "./RigidBody.hpp"
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include "../Math/MatrixSupport.hpp"
using namespace Edge;
RigidBody::RigidBody() :
m_Position(3),
m_CountStateVectors(6),
m_Rotate(3,3),
m_LinearMomentum(3),
m_AngularMomentum(3)
{
}
void
RigidBody::GetState(StateType& State)
{
// Copy the elements of the member variables that describe the state of
// the rigid body into the state vector.
StateType::iterator it = State.begin();
if (State.size() != m_CountStateVectors)
{
State.resize(m_CountStateVectors);
}
*it++ = m_Position;
*it++ = bnu::column(m_Rotate, 0);
*it++ = bnu::column(m_Rotate, 1);
*it++ = bnu::column(m_Rotate, 2);
*it++ = m_AngularMomentum;
*it = m_LinearMomentum;
}
void
RigidBody::GetStateDerivative(StateType& State)
{
//Work out the state derivatives and place them in State
StateType::iterator it = State.begin();
bnu::vector<double> AngularMomentum;
bnu::vector<double> Temp0;
bnu::vector<double> Temp1;
if (State.size() != m_CountStateVectors)
{
State.resize(m_CountStateVectors);
}
bnu::vector<double> LinearVelocity(m_LinearMomentum/m_Mass);
/* Inertia Tensor = R*IBodyInv*RTranspose*/
bnu::matrix<double> InertiaTensorInv((bnu::prod(m_Rotate, m_BodySpaceInertiaTensorInv)));
InertiaTensorInv = bnu::prod(InertiaTensorInv, bnu::trans(m_Rotate));
/* omega = IInv * angularmomentum*/
bnu::vector<double> Omega(bnu::prod(InertiaTensorInv, m_AngularMomentum));
*it++ = LinearVelocity;
/* work out the derivative of R(t) and copy the result into the state array*/
Temp0 = bnu::column(m_Rotate, 0);
Cross(m_AngularMomentum, Temp0, Temp1);
*it++ = Temp1;
Temp0 = bnu::column(m_Rotate, 1);
Cross(m_AngularMomentum, Temp0, Temp1);
*it++ = Temp1;
Temp0 = bnu::column(m_Rotate, 2);
Cross(m_AngularMomentum, Temp0, Temp1);
*it++ = Temp1;
/* copy force and torque into the array */
*it++ = m_Force;
*it++ = m_Torque;
}
| [
"sashang@4efb47e3-d0fd-0310-a049-b1a20f27ebe6"
] | [
[
[
1,
75
]
]
] |
d0fceaf55ac94b4893a2d2a2dc421cd296e2c3e9 | 6188f1aaaf5508e046cde6da16b56feb3d5914bc | /CamFighter/Graphics/D3D/TextureD3D.cpp | e77fd9e998dee8657eb2a55bacdeea1852da35f2 | [] | no_license | dogtwelve/fighter3d | 7bb099f0dc396e8224c573743ee28c54cdd3d5a2 | c073194989bc1589e4aa665714c5511f001e6400 | refs/heads/master | 2021-04-30T15:58:11.300681 | 2011-06-27T18:51:30 | 2011-06-27T18:51:30 | 33,675,635 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,988 | cpp | #ifdef USE_D3D
#include "Texture.h"
#include "../../Utils/Utils.h" // string case compare
#include <D3dx9tex.h>
using namespace Graphics::D3D;
bool Texture :: Create()
{
assert (ID_DXTexture == 0);
assert (Name.size());
/*
Image *image = NULL;
if (this->image.data == NULL)
{
const char *fname = Name.c_str();
if (strcasecmp(fname + Name.size() - 4, ".bmp"))
image = LoadTGA( fname );
else
image = LoadBMP( fname );
if (!image) return false;
}
else
image = &this->image;
Width = image->sizeX;
Height = image->sizeY;
int components = 3;
D3DFORMAT format = 0;
switch (image->format)
{
case Image::FT_RGB8:
format = D3DFMT_R8G8B8;
components = 3;
break;
case Image::FT_RGBA8:
format = D3DFMT_A8R8G8B8;
components = 4;
break;
}
int size = components * image->sizeX * image->sizeY;
*/
if (D3D_OK !=
D3DXCreateTextureFromFile(Graphics::D3D::d3ddev, Name.c_str(), &ID_DXTexture)
/*
D3DXCreateTextureFromFileInMemoryEx(
Graphics::D3D::d3ddev,
image->data,
size,
image->sizeX,
image->sizeY,
D3DX_DEFAULT, // generate mipmaps
0,
format,
D3DPOOL_MANAGED,
D3DX_FILTER_LINEAR,
D3DX_FILTER_LINEAR,
0,
NULL,
NULL,
&ID_DXTexture)
*/
)
{
/*if (image != &this->image)
{
image->FreeData();
delete image;
}*/
return false;
}
/*
// Generate 1 texture ID
glGenTextures(1, &ID_GLTexture);
// Set texture as current
glBindTexture(GL_TEXTURE_2D, ID_GLTexture);
// Modulation mode
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// Scaling filters (during the drawing)
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // MAG_FILTER = magnified filter : when the texture is enlarged
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); // MIN_FILTER = minimized filter : when the texture is shrinked
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// Wraping mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, image->repeatX ? GL_REPEAT : GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, image->repeatY ? GL_REPEAT : GL_CLAMP);
GLint components = 3, format = 0;
GLenum type = 0, colorOrder = 0;
switch (image->type)
{
case Image::TP_UNSIGNED_BYTE:
type = GL_UNSIGNED_BYTE; break;
}
switch (image->format)
{
case Image::FT_RGB8:
format = GL_RGB8;
components = 3;
break;
case Image::FT_RGBA8:
format = GL_RGBA8;
components = 4;
break;
}
switch (image->colorOrder)
{
case Image::CO_RGB:
colorOrder = GL_RGB; break;
case Image::CO_RGBA:
colorOrder = GL_RGBA; break;
case Image::CO_BGR:
colorOrder = GL_BGR_EXT; break;
case Image::CO_BGRA:
colorOrder = GL_BGRA_EXT; break;
}
// Generates the texture
if(FL_MipMap)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
gluBuild2DMipmaps(GL_TEXTURE_2D, //target
components, //number of combonents 1 - 4
image->sizeX, //image size
image->sizeY,
colorOrder, //format (color order)
type,
image->data); //picture represented as a byte array
}
else
{
// Set the properties of the texture : size, color type...
glTexImage2D(GL_TEXTURE_2D, //target
0, //level : usually left to zero
format, //internal format
image->sizeX, //image size
image->sizeY,
0, //0 : no border
colorOrder, //format (color order)
type,
image->data); //picture represented as a byte array
}*/
/*
if (image != &this->image)
{
image->FreeData();
delete image;
}
*/
return true;
}
void Texture :: Dispose( void )
{
if (ID_DXTexture != 0)
{
ID_DXTexture->Release();
ID_DXTexture = 0;
}
image.FreeData();
}
#endif
| [
"darekmac@f75eed02-8a0f-11dd-b20b-83d96e936561"
] | [
[
[
1,
167
]
]
] |
66ed693831da20d4c1157d979dcb97c0f88a7a4c | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/webinit.h | 44a221b825e348e488a9af035793afbe57ea094b | [] | no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,363 | h | // Borland C++ Builder
// Copyright (c) 1995, 2001 by Borland International
// All rights reserved
#ifndef __WEBINIT_H
#define __WEBINIT_H
#include <vcl.h>
#include <WebFact.hpp>
#include <HTTPApp.hpp>
class TWebAppPageInit {
public:
__fastcall TWebAppPageInit(
TMetaClass* AComponentClass,
TWebModuleCacheMode ACacheMode,
TWebPageAccess AAccess,
const AnsiString APageFile = ".html",
const AnsiString APageName = "",
const AnsiString ACaption = "",
const AnsiString ADescription = "",
const AnsiString AViewAccess = "");
};
class TWebPageInit {
public:
__fastcall TWebPageInit(
TMetaClass* AComponentClass,
TWebModuleCreateMode ACreateMode,
TWebModuleCacheMode ACacheMode,
TWebPageAccess AAccess,
const AnsiString APageFile = ".html",
const AnsiString APageName = "",
const AnsiString ACaption = "",
const AnsiString ADescription = "",
const AnsiString AViewAccess = "");
};
class TWebDataModuleInit {
public:
__fastcall TWebDataModuleInit(
TMetaClass* AComponentClass,
TWebModuleCreateMode ACreateMode,
TWebModuleCacheMode ACacheMode);
};
class TWebAppDataModuleInit {
public:
__fastcall TWebAppDataModuleInit(
TMetaClass* AComponentClass,
TWebModuleCacheMode ACacheMode);
};
#endif // __WEBINIT_H
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
] | [
[
[
1,
57
]
]
] |
73d8009a5c4e589fc80d3af876c0bf65212d64f9 | 6eb80649be76f2563df085e4672f5c8bc18602ff | /DitherLibrary/DitherLibrary/Bitmap.cpp | ebd1ac814b98e49dbe928799d72c6bcf5b9a21a0 | [] | no_license | yeuchi/volumehistogram | b664b054a83dc1806949adb859a6edd84a23a9ec | 8248cf473532251d5545284f2b3f0d86470683db | refs/heads/master | 2016-09-05T20:59:11.582498 | 2011-10-16T17:46:09 | 2011-10-16T17:46:09 | 32,119,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include "StdAfx.h"
#include "Bitmap.h"
Bitmap::Bitmap(void)
{
}
Bitmap::Bitmap(char *szBuf,
long lSize) {
}
Bitmap::Bitmap(long lWidth,
long lHeight,
int iDepth) {
}
Bitmap::~Bitmap(void)
{
}
long getPixel(int x, int y) {
long value;
return value;
}
bool setPixel(int x, int y, long value) {
return true;
}
| [
"[email protected]@6a91499e-ffab-11dd-bc25-5f29055a2a2d"
] | [
[
[
1,
28
]
]
] |
725885978497a28208a971cbc36f8d8a4f1d924d | 677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f | /SolidSBCNetLib/stdafx.cpp | 47b0e2509f1648242b984c91d71f00ce4fd42194 | [] | no_license | M0WA/SolidSBC | 0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419 | 3e9682e90a22650e12338785c368ed69a9cac18b | refs/heads/master | 2020-04-19T14:40:36.625222 | 2011-12-02T01:50:05 | 2011-12-02T01:50:05 | 168,250,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | // stdafx.cpp : source file that includes just the standard includes
// SolidSBCNetLib.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"admin@bd7e3521-35e9-406e-9279-390287f868d3"
] | [
[
[
1,
5
]
]
] |
ab9ab5ea21eff702a8a273123f008814cba12137 | 71db16f07e91c3d49691f99c3edbfcba6a604189 | /FahProxy/WorkUnit.cpp | 9f18a46336cfb10d6eaa9109d4cbd8559fc20dbe | [] | no_license | jaboles/fahproxy | 503832879d9c1081e69b642d8cfe32fd0334a3b2 | 131b97ddf86220e4ba52878ba22d06f97003a023 | refs/heads/master | 2022-12-07T13:26:03.522052 | 2008-08-26T11:29:01 | 2008-08-26T11:29:01 | 290,090,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,058 | cpp | #include "WorkUnit.h"
#include "Utils.h"
using namespace FahProxy;
using namespace System;
using namespace System::IO;
WorkUnit::WorkUnit(String^ filename)
{
m_baseFilename = filename;
m_path = String::Concat(System::Environment::GetEnvironmentVariable("appdata"), "\\FahProxy\\", m_baseFilename);
String^ wuDataFilename = String::Concat(m_path, ".wu");
FileInfo^ fi = gcnew FileInfo(wuDataFilename);
m_wuDataSize = fi->Length;
m_time = fi->CreationTime;
// Read data
Stream^ fs = GetDataStream();
m_info = gcnew array<unsigned char, 1>(FAH_RESPONSE_BUFFER_SIZE);
fs->Read(m_info, 0, m_info->Length);
fs->Close();
// Read metadata
fs = gcnew FileStream(String::Concat(m_path, ".txt"), FileMode::Open, FileAccess::Read);
m_uploadHost = Utils::ReadLineFromStream(fs);
m_uploadPort = Convert::ToInt32(Utils::ReadLineFromStream(fs));
m_hostReceivedFrom = Utils::ReadLineFromStream(fs);
fs->Close();
}
WorkUnit::~WorkUnit()
{
}
DateTime WorkUnit::GetTime()
{
return m_time;
}
int WorkUnit::GetDataSize()
{
return m_wuDataSize;
}
System::String^ WorkUnit::GetHostReceivedFrom()
{
return m_hostReceivedFrom;
}
System::String^ WorkUnit::GetUserId()
{
array<int,1>^ a = gcnew array<int,1>(8);
Array::Copy(m_info, 288, a, 0, 8);
__int64 userId = 0;
for (int i = 0; i < 8; i++)
{
userId += ((__int64)a[i] << ((7-i) * 8));
}
userId -= GetMachineId();
return userId.ToString("X");
}
String^ WorkUnit::GetUsername()
{
return System::Text::Encoding::ASCII->GetString(m_info, 160, 64);
}
int WorkUnit::GetMachineId()
{
return (int)m_info[87];
}
String^ WorkUnit::GetTeam()
{
return System::Text::Encoding::ASCII->GetString(m_info, 224, 64);
}
System::String^ WorkUnit::GetUploadHost()
{
return m_uploadHost;
}
int WorkUnit::GetUploadPort()
{
return m_uploadPort;
}
System::IO::Stream^ WorkUnit::GetDataStream()
{
String^ filename = String::Concat(m_path, ".wu");
return gcnew FileStream(filename, FileMode::Open, FileAccess::Read);
}
System::IO::Stream^ WorkUnit::GetTranslatedResponseStream()
{
MemoryStream^ ms = gcnew MemoryStream();
array<unsigned char, 1>^ a = gcnew array<unsigned char, 1>(4);
// decimal 400 (offset 0)
ms->WriteByte(0x00); ms->WriteByte(0x00); ms->WriteByte(0x01); ms->WriteByte(0x90);
// decimal 17 (offset 4)
ms->WriteByte(0x00); ms->WriteByte(0x00); ms->WriteByte(0x00); ms->WriteByte(0x11);
// ? (offset 8)
Array::Copy(m_info, 8, a, 0, 4);
Array::Reverse(a);
ms->Write(a, 0, a->Length);
// ? (offset 12)
Array::Copy(m_info, 12, a, 0, 4);
Array::Reverse(a);
ms->Write(a, 0, a->Length);
// zeros (offset 16)
ms->Write(m_info, 16, 64);
// Machine ID (offset 80)
ms->Write(m_info, 80, 8);
// IP address (offset 88)
ms->Write(m_info, 88, 4);
// Zeros (offset 92)
ms->Write(m_info, 92, 68);
// Username (offset 160)
ms->Write(m_info, 160, 64);
// Team number as string (offset 224)
ms->Write(m_info, 224, 64);
// User ID + machine ID
ms->Write(m_info, 288, 8);
// Zeros (offset 296)
ms->Write(m_info, 296, 8);
// ? (reversed in response) (offset 304)
Array::Copy(m_info, 304, a, 0, 4);
Array::Reverse(a);
ms->Write(a, 0, a->Length);
// ? (reversed in response) (offset 308)
Array::Copy(m_info, 308, a, 0, 4);
Array::Reverse(a);
ms->Write(a, 0, a->Length);
// ? (reversed in response) (offset 312)
Array::Copy(m_info, 312, a, 0, 4);
Array::Reverse(a);
ms->Write(a, 0, a->Length);
// ? (reversed in response) (offset 316)
Array::Copy(m_info, 316, a, 0, 4);
Array::Reverse(a);
ms->Write(a, 0, a->Length);
// Zeros (offset 320)
ms->Write(m_info, 320, 24);
// IP address (offset 344)
ms->Write(m_info, 344, 4);
// Zeros (offset 348)
ms->Write(m_info, 348, 8);
// ? (reversed in response) (offset 356)
Array::Copy(m_info, 356, a, 0, 4);
Array::Reverse(a);
ms->Write(a, 0, a->Length);
// Zeros (offset 360)
ms->Write(m_info, 360, 80);
// decimal 513? (offset 440)
ms->Write(m_info, 440, 8);
// Zeros (offset 448)
ms->Write(m_info, 448, 64);
// There. that should be 512 bytes.
ms->Seek(0, SeekOrigin::Begin);
return ms;
}
void WorkUnit::WriteReceipt(array<unsigned char,1>^ receiptBuffer)
{
Stream^ f = gcnew FileStream(String::Concat(m_path, ".receipt"), FileMode::Create);
f->Write(receiptBuffer, 0, receiptBuffer->Length);
f->Close();
}
void WorkUnit::WriteSimulatedResponse()
{
Stream^ s = GetTranslatedResponseStream();
array<unsigned char,1>^ buf = gcnew array<unsigned char,1>(s->Length);
s->Read(buf, 0, s->Length);
s->Close();
Stream^ f = gcnew FileStream(String::Concat(m_path, ".simulatedResponse"), FileMode::Create);
f->Write(buf, 0, buf->Length);
f->Close();
}
void WorkUnit::CleanUpFile()
{
try
{
File::Delete(String::Concat(m_path, ".wu"));
File::Delete(String::Concat(m_path, ".txt"));
}
catch (System::IO::IOException^)
{
// Ignore.
}
} | [
"jb@dc620d95-ca3a-fc45-9de6-42b3e20515ab"
] | [
[
[
1,
223
]
]
] |
a8567414e06d85704a1b3cc2cb5f6f9b5f4ab97f | 723202e673511cf9f243177d964dfeba51cb06a3 | /09/oot/epa_labs/l2/src/Insert_Text.cpp | 1f1c8ee90c77c15996588eba9d45ce7b8a50fe48 | [] | no_license | aeremenok/a-team-777 | c2ffe04b408a266f62c523fb8d68c87689f2a2e9 | 0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b | refs/heads/master | 2020-12-24T16:50:12.178873 | 2009-06-16T14:55:41 | 2009-06-16T14:55:41 | 32,388,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,825 | cpp | // Insert_Text.cpp : implementation file
//
#include "stdafx.h"
#include "Sketcher.h"
#include "Insert_Text.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// Insert_Text dialog
Insert_Text::Insert_Text(CWnd* pParent /*=NULL*/)
: CDialog(Insert_Text::IDD, pParent)
{
//{{AFX_DATA_INIT(Insert_Text)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void Insert_Text::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(Insert_Text)
DDX_Text(pDX, IDC_TEXT, insert_text);
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(Insert_Text, CDialog)
//{{AFX_MSG_MAP(Insert_Text)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Insert_Text message handlers
void Insert_Text::OnOK()
{
// TODO: Add extra validation here
CDialog::OnOK();
}
void Insert_Text::OnCancel()
{
// TODO: Add extra cleanup here
CDialog::OnCancel();
}
void Insert_Text::setText(CString str)
{
/* CEdit * pSpin;
pSpin = (CEdit*)GetDlgItem(IDC_TEXT);
pSpin->SetDlgItemText(IDC_TEXT,str);
*/
}
CString Insert_Text::getText(){
/*CEdit * pSpin;
pSpin = (CEdit*)GetDlgItem(IDC_TEXT);
char* s = new char[20];
pSpin->GetDlgItemText(IDC_TEXT,s,20);
return s;
*/
return insert_text;
}
BOOL Insert_Text::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| [
"emmanpavel@9273621a-9230-0410-b1c6-9ffd80c20a0c"
] | [
[
[
1,
86
]
]
] |
3743e4ba0a7db551d53699e8e5b7793f9e4ff823 | 74bc09bccf109de71fd3bdd36e5907d54a11dd2d | /Lixo/cMap.h | a4317b1be171fd539f0b68d0aed0d566f16f0de0 | [] | no_license | CrociDB/Lixo-no-Lixo | 881c25513f248dc5b81f8b947f2156be9a7f08fc | 1868c05a2c2752c7ec877cbc9bc67675067d97ef | refs/heads/master | 2016-09-06T07:45:21.184909 | 2009-10-12T18:15:24 | 2009-10-12T18:15:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 330 | h | #include <gamespace.h>
#include <windows.h>
#include "cTrash.h"
class cMap
{
private:
GAMESPACE_VIDEO_HANDLER *gsVideo;
cTrash *trash;
GS_SPRITE back;
GS_SPRITE ball;
GS_SPRITE can;
int x, y;
public:
cMap(GAMESPACE_VIDEO_HANDLER *pVideo, cTrash *pTrash);
void run();
}; | [
"[email protected]"
] | [
[
[
1,
21
]
]
] |
66e26bff01e1bf80f5d8a25898dbb29a36122432 | 45229380094a0c2b603616e7505cbdc4d89dfaee | /wavelets/edges_src/src/Lib/mbior97.cpp | 25f28ad7f63567d1548586e9995f475a4b8e4256 | [] | no_license | xcud/msrds | a71000cc096723272e5ada7229426dee5100406c | 04764859c88f5c36a757dbffc105309a27cd9c4d | refs/heads/master | 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 19,614 | cpp |
#include "stdafx.h"
#include "vec1d.h"
#include "basefwt.h"
#include "mbior97.h"
//bior97 filter////////////////////////////////////////////////////////////////////////////////////////
const float mBior97::tH[9] = { 0.026748757410810f, //-4
-0.016864118442875f, //-3
-0.078223266528990f, //-2
0.266864118442875f, //-1
0.602949018236360f, // 0
0.266864118442875f, // 1
-0.078223266528990f, // 2
-0.016864118442875f, // 3
0.026748757410810f
}; // 4
const float mBior97::tG[9] = { 0.0f, //-4
0.0f, //-3
0.045635881557125f, //-2
-0.02877176311425f, //-1
-0.295635881557125f, // 0
0.5575435262285f, // 1
-0.295635881557125f, // 2
-0.02877176311425f, // 3
0.045635881557125f
}; // 4
const float mBior97::H[9] = { -0.045635881557125f, //-3
-0.02877176311425f, //-2
0.295635881557125f, //-1
0.5575435262285f, // 0
0.295635881557125f, // 1
-0.02877176311425f, // 2
-0.045635881557125f, // 3
0.0f, // 4
0.0f
}; // 5
const float mBior97::G[9] = { 0.026748757410810f, //-3
0.016864118442875f, //-2
-0.078223266528990f, //-1
-0.266864118442875f, // 0
0.602949018236360f, // 1
-0.266864118442875f, // 2
-0.078223266528990f, // 3
0.016864118442875f, // 4
0.026748757410810f
}; // 5
//bior97 filter////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////constructors/destructors///////////////////////////////////////////////////////////////////
mBior97::mBior97() : BaseFWT2D(L"bior97", tH, 9, 4, tG, 9, 4, H, 9, 3, G, 9, 3)
{
}
///////////////////////////////////constructors/destructors///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////transforms/////////////////////////////////////////////////////////////////////
void mBior97::transrows(char** dest, char** sour, unsigned int w, unsigned int h) const
{
char srck0[8] = {0, 0, 0, 0, 0, 0, 0, 0};
//int n;
float s, d;
unsigned int w2 = w / 2;
const vec1D& tH = gettH();
const vec1D& tG = gettG();
for (unsigned int y = 0; y < h; y++) {
//k=0
unsigned int k = 0;
srck0[0] = sour[y][4];
srck0[1] = sour[y][3];
srck0[2] = sour[y][2];
srck0[3] = sour[y][1];
s = conv(tH.data(), srck0);
s += conv(tH.data() + 4, &sour[y][2*k]);
s += tH[4] * (float)sour[y][2*k + 4];
d = conv(tG.data(), srck0);
d += conv(tG.data() + 4, &sour[y][2*k]);
d += tG[4] * (float)sour[y][2*k + 4];
dest[y][k] = mmxround(s);
dest[y][k+w2] = mmxroundTH(d);
//k=1
k = 1;
srck0[0] = sour[y][2];
srck0[1] = sour[y][1];
srck0[2] = sour[y][0];
srck0[3] = sour[y][1];
s = conv(tH.data(), srck0);
s += conv(tH.data() + 4, &sour[y][2*k]);
s += tH[4] * (float)sour[y][2*k + 4];
d = conv(tG.data(), srck0);
d += conv(tG.data() + 4, &sour[y][2*k]);
d += tG[4] * (float)sour[y][2*k + 4];
dest[y][k] = mmxround(s);
dest[y][k+w2] = mmxroundTH(d);
//k=2, k<w2-2
for (k = 2; k < w2 - 2; k++) {
s = conv(tH.data(), &sour[y][2*k - 4]);
s += conv(tH.data() + 4, &sour[y][2*k]);
s += tH[4] * (float)sour[y][2*k + 4];
d = conv(tG.data(), &sour[y][2*k - 4]);
d += conv(tG.data() + 4, &sour[y][2*k]);
d += tG[4] * (float)sour[y][2*k + 4];
dest[y][k] = mmxround(s);
dest[y][k+w2] = mmxroundTH(d);
}
//k=w2-2
k = w2 - 2;
s = conv(tH.data(), &sour[y][2*k - 4]);
s += conv(tH.data() + 4, &sour[y][2*k]);
s += tH[4] * (float)sour[y][2*k + 4 - 2];
d = conv(tG.data(), &sour[y][2*k - 4]);
d += conv(tG.data() + 4, &sour[y][2*k]);
d += tG[4] * (float)sour[y][2*k + 4 - 2];
dest[y][k] = mmxround(s);
dest[y][k+w2] = mmxroundTH(d);
//k=w2-1
k = w2 - 1;
srck0[0] = sour[y][2*k];
srck0[1] = sour[y][2*k+1];
srck0[2] = sour[y][2*k];
srck0[3] = sour[y][2*k-1];
s = conv(tH.data(), &sour[y][2*k - 4]);
s += conv(tH.data() + 4, srck0);
s += tH[4] * (float)sour[y][2*k - 2];
d = conv(tG.data(), &sour[y][2*k - 4]);
d += conv(tG.data() + 4, srck0);
d += tG[4] * (float)sour[y][2*k - 2];
dest[y][k] = mmxround(s);
dest[y][k+w2] = mmxroundTH(d);
}
}
void mBior97::transcols(char** dest, char** sour, unsigned int w, unsigned int h) const
{
float fz = 0.0f;
int n;
float s, d;
__m128 ms, md;
unsigned int h2 = h / 2;
const vec1D& tH = gettH();
const vec1D& tG = gettG();
for (unsigned int x = 0; x < w / 4; x++) { //x<w/4 x = 4*x
for (unsigned int k = 0; k < h2; k++) {
ms = _mm_load_ss(&fz);
md = ms;
for (int m = -4; m <= 4; m++) {
n = 2 * k + m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
ms = _mm_add_ps(ms, _mm_mul_ps(_mm_load_ps1(tH.data(m)), _mm_cvtpi8_ps(*(__m64 *)(&sour[n][4*x]))));
}
for (int m = -2; m <= 4; m++) {
n = 2 * k + m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
md = _mm_add_ps(md, _mm_mul_ps(_mm_load_ps1(tG.data(m)), _mm_cvtpi8_ps(*(__m64 *)(&sour[n][4*x]))));
}
if (4*x < w / 2) {
if ((w / 2) - (4*x) >= 4)
mmxround4(&dest[k][4*x], ms);
else
mmxround4TH(&dest[k][4*x], ms, (w / 2) - (4*x)); //skip first from LL part 10/2-4=1 [lo] o o o o * | * * * o o [hi]
} else
mmxround4TH(&dest[k][4*x], ms);
mmxround4TH(&dest[k+h2][4*x], md);
}
}
_mm_empty();
//odd remainder
for (unsigned int x = w - (w % 4); x < w; x++) {
for (unsigned int k = 0; k < h2; k++) {
s = 0;
d = 0;
for (int m = -4; m <= 4; m++) {
n = 2 * k + m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
s += tH[m] * float(sour[n][x]);
}
for (int m = -2; m <= 4; m++) {
n = 2 * k + m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
d += tG[m] * float(sour[n][x]);
}
if (x < w / 2)
dest[k][x] = mmxround(s);
else
dest[k][x] = mmxroundTH(s); //is this needed? hi band were TH'ed on transrows
dest[k+h2][x] = mmxroundTH(d); //is this needed? hi band were TH'ed on transrows on x>w/2
}
}
}
///////////////////////////////////////////////transforms/////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////synths//////////////////////////////////////////////////////////////////////////
void mBior97::synthrows(char** dest, char** sour, unsigned int w, unsigned int h) const //w,h of the LO part
{
char srclo[8] = {0, 0, 0, 0, 0, 0, 0, 0};
char srchi[8] = {0, 0, 0, 0, 0, 0, 0, 0};
//int n;
float s2k, s2k1;
const vec1D& H2m = getH2m();
const vec1D& G2m = getG2m();
const vec1D& H2m1 = getH2m1();
const vec1D& G2m1 = getG2m1();
for (unsigned int y = 0; y < 2*h; y++) {
//k = [0; 2)
for (unsigned int k = 0; k < 2; k++) {
if (k == 0) {
srclo[0] = sour[y][2];
srclo[1] = sour[y][1];
srclo[2] = sour[y][0];
srclo[3] = sour[y][1];
srclo[4] = sour[y][2];
srchi[0] = sour[y][2+w];
srchi[1] = sour[y][1+w];
srchi[2] = sour[y][0+w];
srchi[3] = sour[y][1+w];
srchi[4] = sour[y][2+w];
} else if (k == 1) {
srclo[0] = sour[y][1];
srclo[1] = sour[y][0];
srclo[2] = sour[y][1];
srclo[3] = sour[y][2];
srclo[4] = sour[y][3];
srchi[0] = sour[y][1+w];
srchi[1] = sour[y][0+w];
srchi[2] = sour[y][1+w];
srchi[3] = sour[y][2+w];
srchi[4] = sour[y][3+w];
}
s2k = convr(H2m.data(), srclo); //s2k even H
s2k += convr(G2m.data(), srchi);
s2k1 = convr(H2m1.data(), srclo + 1); //s2k1 odd H
s2k1 += H2m1[H2m1.last()] * float(srclo[0]);
s2k1 += convr(G2m1.data(), srchi + 1); //s2k1 odd G
s2k1 += G2m1[G2m1.last()] * float(srchi[0]);
dest[y][2*k] = mmxround(2.0f * s2k);
dest[y][2*k+1] = mmxround(2.0f * s2k1);
}
//k = [2; w-2)
for (unsigned int k = 2; k < w - 2; k++) {
s2k = convr(H2m.data(), &sour[y][k-2]); //s2k1 odd H
s2k += convr(G2m.data(), &sour[y][k-2+w]); //s2k even G
s2k1 = convr(H2m1.data(), &sour[y][k-1]); //s2k1 odd H
s2k1 += H2m1[H2m1.last()] * float(sour[y][k-2]);
s2k1 += convr(G2m1.data(), &sour[y][k-1+w]); //s2k1 odd G
s2k1 += G2m1[G2m1.last()] * float(sour[y][k-2+w]);
dest[y][2*k] = mmxround(2.0f * s2k);
dest[y][2*k+1] = mmxround(2.0f * s2k1);
}
//k = [w-2; w)
for (unsigned int k = w - 2; k < w; k++) {
if (k == w - 2) {
srclo[0] = sour[y][k-2];
srclo[1] = sour[y][k-1];
srclo[2] = sour[y][k];
srclo[3] = sour[y][k+1];
srclo[4] = sour[y][k];
srchi[0] = sour[y][k-2+w];
srchi[1] = sour[y][k-1+w];
srchi[2] = sour[y][k+w];
srchi[3] = sour[y][k+1+w];
srchi[4] = sour[y][k+w];
} else if (k == w - 1) {
srclo[0] = sour[y][k-2];
srclo[1] = sour[y][k-1];
srclo[2] = sour[y][k];
srclo[3] = sour[y][k-1];
srclo[4] = sour[y][k-2];
srchi[0] = sour[y][k-2+w];
srchi[1] = sour[y][k-1+w];
srchi[2] = sour[y][k+w];
srchi[3] = sour[y][k-1+w];
srchi[4] = sour[y][k-2+w];
}
s2k = convr(H2m.data(), srclo); //s2k even H
s2k += convr(G2m.data(), srchi);
s2k1 = convr(H2m1.data(), srclo + 1); //s2k1 odd H
s2k1 += H2m1[H2m1.last()] * float(srclo[0]);
s2k1 += convr(G2m1.data(), srchi + 1); //s2k1 odd G
s2k1 += G2m1[G2m1.last()] * float(srchi[0]);
dest[y][2*k] = mmxround(2.0f * s2k);
dest[y][2*k+1] = mmxround(2.0f * s2k1);
}
}
}
void mBior97::synthcols(char** dest, char** sour, unsigned int w, unsigned int h) const //w,h of the LO part
{
float fz = 0.0f;
float mul2 = 2.0f;
int n;
float s2k, s2k1;
__m128 ms2k, ms2k1;
unsigned int w2 = 2 * w;
const vec1D& H2m = getH2m();
const vec1D& G2m = getG2m();
const vec1D& H2m1 = getH2m1();
const vec1D& G2m1 = getG2m1();
for (unsigned int x = 0; x < w2 / 4; x++) { //x<w2/2 x = 4*x
for (unsigned int k = 0; k < h; k++) {
ms2k = _mm_load_ss(&fz);
ms2k1 = ms2k;
for (int m = -1; m <= 1; m++) { //s2k even H
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
ms2k = _mm_add_ps(ms2k, _mm_mul_ps(_mm_load_ps1(H2m.data(m)), _mm_cvtpi8_ps(*(__m64 *)(&sour[n][4*x]))));
}
for (int m = -1; m <= 2; m++) { //s2k even G
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
ms2k = _mm_add_ps(ms2k, _mm_mul_ps(_mm_load_ps1(G2m.data(m)), _mm_cvtpi8_ps(*(__m64 *)(&sour[n+h][4*x]))));
}
for (int m = -2; m <= 1; m++) { //s2k1 odd H
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
ms2k1 = _mm_add_ps(ms2k1, _mm_mul_ps(_mm_load_ps1(H2m1.data(m)), _mm_cvtpi8_ps(*(__m64 *)(&sour[n][4*x]))));
}
for (int m = -2; m <= 2; m++) { //s2k1 odd G
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
ms2k1 = _mm_add_ps(ms2k1, _mm_mul_ps(_mm_load_ps1(G2m1.data(m)), _mm_cvtpi8_ps(*(__m64 *)(&sour[n+h][4*x]))));
}
__m128 mmul2 = _mm_load_ps1(&mul2);
mmxround4(&dest[2*k][4*x], _mm_mul_ps(ms2k, mmul2));
mmxround4(&dest[2*k+1][4*x], _mm_mul_ps(ms2k1, mmul2));
}
}
_mm_empty();
//odd remainder
for (unsigned int x = w2 - (w2 % 4); x < w2; x++) {
for (unsigned int k = 0; k < h; k++) {
s2k = 0;
s2k1 = 0;
for (int m = -1; m <= 1; m++) { //s2k even H
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
s2k += H2m[m] * float(sour[n][x]);
}
for (int m = -1; m <= 2; m++) { //s2k even G
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
s2k += G2m[m] * float(sour[n+h][x]);
}
for (int m = -2; m <= 1; m++) { //s2k1 odd H
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
s2k1 += H2m1[m] * float(sour[n][x]);
}
for (int m = -2; m <= 2; m++) { //s2k1 odd G
n = k - m;
if (n < 0) n = 0 - n;
if (n >= (int)h) n -= 2 * (1 + n - h);
s2k1 += G2m1[m] * float(sour[n+h][x]);
}
dest[2*k][x] = mmxround(2.0f * s2k);
dest[2*k+1][x] = mmxround(2.0f * s2k1);
}
}
}
//////////////////////////////////////////////synths//////////////////////////////////////////////////////////////////////////
| [
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
] | [
[
[
1,
454
]
]
] |
9b7edb41a6e9dcc477c9b0afa4efe9ee10993ba0 | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /QueryLibrary/Query/And.cpp | 9f846da11e6b5c3f37c52dc529b0f622ce53969e | [] | no_license | asankaf/scalable-data-mining-framework | e46999670a2317ee8d7814a4bd21f62d8f9f5c8f | 811fddd97f52a203fdacd14c5753c3923d3a6498 | refs/heads/master | 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | cpp | #include "And.h"
And::And()
{
}
And::And(string name)
{
this->name=name;
this->type=TYPEAND;
}
And::~And()
{
}
string And::getName()
{
return name;
}
string And::toString()
{
return name;
} | [
"buddhi.1986@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
] | [
[
[
1,
23
]
]
] |
4ae291c374b789b62e43d31a5510969c01787786 | cfc9acc69752245f30ad3994cce0741120e54eac | /bikini/include/bikini/display/swf/tagcodes.hpp | 39d4450cfed45c58589d1948a725802f8bc46db4 | [] | no_license | Heartbroken/bikini-iii | 3b7852d1af722b380864ac87df57c37862eb759b | 93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739 | refs/heads/master | 2020-03-28T00:41:36.281253 | 2009-04-30T14:58:10 | 2009-04-30T14:58:10 | 37,190,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,915 | hpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008 Viktor Reutzky
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#pragma once
namespace tag { /*-------------------------------------------------------------------------------*/
enum code {
End = 0,
ShowFrame = 1,
DefineShape = 2,
PlaceObject = 4,
RemoveObject = 5,
DefineBits = 6,
DefineButton = 7,
JPEGTables = 8,
SetBackgroundColor = 9,
DefineFont = 10,
DefineText = 11,
DoAction = 12,
DefineFontInfo = 13,
DefineSound = 14,
StartSound = 15,
DefineButtonSound = 17,
SoundStreamHead = 18,
SoundStreamBlock = 19,
DefineBitsLossless = 20,
DefineBitsJPEG2 = 21,
DefineShape2 = 22,
DefineButtonCxform = 23,
Protect = 24,
PlaceObject2 = 26,
RemoveObject2 = 28,
DefineShape3 = 32,
DefineText2 = 33,
DefineButton2 = 34,
DefineBitsJPEG3 = 35,
DefineBitsLossless2 = 36,
DefineEditText = 37,
DefineSprite = 39,
FrameLabel = 43,
SoundStreamHead2 = 45,
DefineMorphShape = 46,
DefineFont2 = 48,
ExportAssets = 56,
ImportAssets = 57,
EnableDebugger = 58,
DoInitAction = 59,
DefineVideoStream = 60,
VideoFrame = 61,
DefineFontInfo2 = 62,
EnableDebugger2 = 64,
ScriptLimits = 65,
SetTabIndex = 66,
FileAttributes = 69,
PlaceObject3 = 70,
ImportAssets2 = 71,
DefineFontAlignZones = 73,
CSMTextSettings = 74,
DefineFont3 = 75,
SymbolClass = 76,
Metadata = 77,
DefineScalingGrid = 78,
DoABC = 82,
DefineShape4 = 83,
DefineMorphShape2 = 84,
DefineSceneAndFrameLabelData = 86,
DefineBinaryData = 87,
DefineFontName = 88,
StartSound2 = 89,
};
} /* tag ----------------------------------------------------------------------------------------*/ | [
"my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef"
] | [
[
[
1,
78
]
]
] |
e251f8f64236ed08871ab5fb31b5bebf4afc35d2 | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /src/CoCoapplication.cpp | ff2fa95d234774aa3dbb441d01889456c81decbe | [] | no_license | flaithbheartaigh/wapbrowser | ba09f7aa981d65df810dba2156a3f153df071dcf | b0d93ce8517916d23104be608548e93740bace4e | refs/heads/master | 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,682 | cpp | /*
============================================================================
Name : CoCoApplication.cpp
Author : 浮生若茶
Version :
Copyright : Your copyright notice
Description : Main application class
============================================================================
*/
// INCLUDE FILES
#include "CoCoDocument.h"
#include "CoCoApplication.h"
#include "PreDefine.h"
// ============================ MEMBER FUNCTIONS ===============================
// UID for the application;
// this should correspond to the uid defined in the mmp file
#ifdef __SERIES60_3X__
const TUid KUidCoCoApp = { 0xe000bf65 };
#else
const TUid KUidCoCoApp = { 0x03AF99E6 };
#endif
// -----------------------------------------------------------------------------
// CCoCoApplication::CreateDocumentL()
// Creates CApaDocument object
// -----------------------------------------------------------------------------
//
CApaDocument* CCoCoApplication::CreateDocumentL()
{
// Create an CoCo document, and return a pointer to it
return (static_cast<CApaDocument*>
( CCoCoDocument::NewL( *this ) ) );
}
// -----------------------------------------------------------------------------
// CCoCoApplication::AppDllUid()
// Returns application UID
// -----------------------------------------------------------------------------
//
TUid CCoCoApplication::AppDllUid() const
{
// Return the UID for the CoCo application
return KUidCoCoApp;
}
CDictionaryStore* CCoCoApplication::OpenIniFileLC(RFs& aFs) const
{
return CEikApplication::OpenIniFileLC(aFs);
}
// End of File
| [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
] | [
[
[
1,
53
]
]
] |
94a6e99a18a7b4aa360bbbe9ac484a3c733cb13d | 6ff5f4e9353d07e744e761351670d5e38a0b9247 | /Map.h | 2f639d9582188fb89fdeed6c3e2862818a8a314b | [] | no_license | RonanRaven/blockpuzzle-ver-awesomer | 104b2608dd57fe2e523ae35d114437b87698c1be | cdf5de54295fbc49da13ff34aba9f9dd60699324 | refs/heads/master | 2021-01-10T15:28:46.673527 | 2008-10-29T02:38:51 | 2008-10-29T02:38:51 | 44,951,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | h | #pragma once
class Map
{
protected:
int col, row;
public:
char** table;
void setAt(int row, int column, char ascii);
char checkAt(int row,int column);
int getrow(){return row;}
int getcol(){return col;}
void setrow(int r){row=r;}
void setcol(int c){col=c;}
void createTable(int row, int column);
void deleteTable();
}; | [
"RonanRaven@357130da-93fe-11dd-8b39-fd4b6f224790"
] | [
[
[
1,
20
]
]
] |
187d81a5891b44f6d898718426cdf6cef71b3622 | e83958019dc97551b07e2a5e9a14426198e6a2d9 | /experiment.cpp | 4df1e1afcf4b9f75ec8c5dfa28ee08d8c10b5aee | [] | no_license | rue-ryuzaki/Extract_CUDA | a31ff2ba142b82f1c8de634f4c598553f762761f | 75e63f03d0837aaa51a025b5429b0d738e3b7b81 | refs/heads/master | 2021-01-16T07:09:49.301981 | 2011-08-06T19:31:16 | 2011-08-06T19:31:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,693 | cpp | // Read file
#include <iostream.h>
#include <fstream.h>
#include <string.h>
using namespace std;
typedef vector<Vector3> coordVec;
void readCoords(coordVec * coords, const char * fileName, const double multiply=1)
{
double x,y,z;
bool x_eq, y_eq, z_eq;
bool mantiss = false;
ifstream fin(fileName);
if (fin)
{
x_eq = true;
y_eq = z_eq = false;
x = y = z = 0;
double mant = 0;
double mul = 10;
char ch;
int sign = 1;
bool change = true;
mantiss = false;
while(fin.get(ch))
{
if (change)
if (ch == '-')
{
sign = -1;
change = false;
continue;
}
else
sign = 1;
if (ch == '.')
{
mantiss = true;
mant = 0;
change = false;
continue;
}
if (ch < '0' || ch > '9')
{
if (x_eq)
x += mant;
else if (y_eq)
y += mant;
else
{
z += mant;
coords->push_back(Vector3(x*multiply,y*multiply,z*multiply));
x = y = z = 0;
}
bool old_x = x_eq;
x_eq = z_eq;
z_eq = y_eq;
y_eq = old_x;
mant = 0;
mul = 10;
mantiss = false;
change = true;
continue;
}
change = false;
if (!mantiss)
{
if (x_eq)
x = x*10 + sign*(int)(ch-'0');
else if (y_eq)
y = y*10 + sign*(int)(ch-'0');
else if (z_eq)
z = z*10 + sign*(int)(ch-'0');
}
else {
mant += (int)(ch-'0')/mul;
mul *= 10;
}
}
}
fin.close();
}
int main()
{
coordVec * coords = new coordVec;
readCoords(coords, "coords.txt");
for (coordVec::size_type i=0; i < coords->size(); i++)
{
cout << (*coords)[i] << endl;
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
99
]
]
] |
e56560c2bc429a82f34a4977c61664fbbd295e8b | c3531ade6396e9ea9c7c9a85f7da538149df2d09 | /Param/include/hj_3rd/hjlib/sparse_old/umf_pack_solver.h | daefe189a16a786b63a6676b1cf55d3705f0adde | [] | no_license | feengg/MultiChart-Parameterization | ddbd680f3e1c2100e04c042f8f842256f82c5088 | 764824b7ebab9a3a5e8fa67e767785d2aec6ad0a | refs/heads/master | 2020-03-28T16:43:51.242114 | 2011-04-19T17:18:44 | 2011-04-19T17:18:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | h | #ifndef HJ_UMF_PACK_SOLVER_H_
#define HJ_UMF_PACK_SOLVER_H_
#include "sparse.h"
class umf_pack_solver : public hj::sparse::solver
{
public:
umf_pack_solver();
bool create(const hj::sparse::spm_csc<double> &A);
virtual bool set_patten(int rows, const zjucad::matrix::matrix<int> &ptr, const zjucad::matrix::matrix<int> &idx);
virtual bool set_value (const zjucad::matrix::matrix<double> &val);
virtual bool solve(const double *b, double *x, int nrhs = 1);
~umf_pack_solver();
protected:
void *numeric_, *symbolic_;
hj::sparse::spm_csc<double> A_;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
38a1b86c3e5e9aa0d554eb6e1fdd139af3bd4042 | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /TileEngine/WorldDat.cpp | a058b67f4e22f7a64a6f1e8cd3c7910ef7565dc5 | [] | no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02T23:07:58.941216 | 2011-10-18T09:22:53 | 2011-10-18T09:22:53 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 12,419 | cpp | #include "builddefines.h"
#ifdef PRECOMPILEDHEADERS
#include "TileEngine All.h"
#else
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include "worlddat.h"
#include "worlddef.h"
#include "tiledef.h"
#include "sys globals.h"
#include "tile surface.h"
#include "fileMan.h"
#include "Debug.h"
#endif
#include <vfs/Core/vfs.h>
#include <vfs/Core/vfs_file_raii.h>
#include "XML_TileSet.hpp"
#include "XMLWriter.h"
void ExportTilesets(vfs::Path const& filename);
// THIS FILE CONTAINS DEFINITIONS FOR TILESET FILES
void SetTilesetThreeTerrainValues();
void SetTilesetFourTerrainValues();
// Snap: This global gives the number of tilesets in JA2SET.DAT
// It is properly initialized in InitEngineTilesets,
// where it is read from JA2SET.DAT header.
UINT8 gubNumSets = MAX_TILESETS;
TILESET gTilesets[ MAX_TILESETS ];
extern bool g_bUseXML_Tilesets;
void InitEngineTilesets( )
{
if(g_bUseXML_Tilesets)
{
const vfs::Path tileset_filename(L"Ja2Set.dat.xml");
if(!getVFS()->fileExists(tileset_filename))
{
SGP_TRYCATCH_RETHROW( ExportTilesets(tileset_filename), L"Could not export tileset XML file");
}
vfs::tReadableFile* file = getVFS()->getReadFile(tileset_filename);
SGP_THROW_IFFALSE(file,
_BS(L"File '") << tileset_filename << L"' does not exist and could not be created" << _BS::wget);
CTilesetReader tileset_reader(gTilesets);
xml_auto::TGenericXMLParser<CTilesetReader> pars(&tileset_reader,NULL);
SGP_TRYCATCH_RETHROW( pars.parseFile(file),
_BS(L"Parser Error in file : ") << file->getPath() << _BS::wget );
}
else
{
UINT32 cnt, cnt2, uiNumFiles;
//FILE *hfile;
HWFILE hfile;
CHAR8 zName[32];
UINT32 uiNumBytesRead;
//OPEN FILE
hfile = FileOpen( "BINARYDATA\\JA2SET.DAT", FILE_ACCESS_READ, FALSE );
if ( !hfile )
{
SET_ERROR( "Cannot open tileset data file" );
return;
}
// READ # TILESETS and compare
FileRead( hfile, &gubNumSets, sizeof( gubNumSets ), &uiNumBytesRead );
// CHECK
if ( gubNumSets > MAX_TILESETS )
{
// Report error
SET_ERROR( "Too many tilesets in the data file" );
return;
}
// READ #files
FileRead( hfile, &uiNumFiles, sizeof( uiNumFiles ), &uiNumBytesRead );
// COMPARE
if ( uiNumFiles != NUMBEROFTILETYPES )
{
// Report error
SET_ERROR( "Number of tilesets slots in code does not match data file" );
return;
}
// Loop through each tileset, load name then files
for ( cnt = 0; cnt < gubNumSets; cnt++ )
{
//Read name
FileRead( hfile, &zName, sizeof( zName ), &uiNumBytesRead );
// Read ambience value
FileRead( hfile, &(gTilesets[ cnt ].ubAmbientID), sizeof( UINT8 ), &uiNumBytesRead );
// Set into tileset
swprintf( gTilesets[ cnt ].zName, L"%S", zName );
// Loop for files
for ( cnt2 = 0; cnt2 < uiNumFiles; cnt2++ )
{
// Read file name
FileRead( hfile, &zName, sizeof( zName ), &uiNumBytesRead );
// Set into database
strcpy( gTilesets[ cnt ].TileSurfaceFilenames[ cnt2 ], zName );
}
}
FileClose( hfile );
}
#ifdef JA2UBMAPS
gTilesets[ TLS_CAVES_1 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetTwoTerrainValues;
gTilesets[ TLS_AIRSTRIP ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_DEAD_AIRSTRIP ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TEMP_14 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TEMP_18 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TEMP_19 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TEMP_26 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TEMP_27 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TEMP_28 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TEMP_29 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_TROPICAL_1 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetFourTerrainValues;
gTilesets[ TEMP_20 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetFourTerrainValues;
#else
// SET CALLBACK FUNTIONS!!!!!!!!!!!!!
gTilesets[ TLS_CAVES_1 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetTwoTerrainValues;
gTilesets[ TLS_AIRSTRIP ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_DEAD_AIRSTRIP ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_PALACE ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_BALIME ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_BALIME_MUSEUM ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_QUEENS_TROPICAL ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_MEDUNA_INNER_TOWN ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_QUEENS_SAM ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_QUEENS_AIRPORT ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetThreeTerrainValues;
gTilesets[ TLS_TROPICAL_1 ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetFourTerrainValues;
gTilesets[ TLS_DESERT_SAM ].MovementCostFnc = (TILESET_CALLBACK)SetTilesetFourTerrainValues;
#endif
}
#ifdef USE_VFS
void ExportTilesets(vfs::Path const& filename)
{
UINT32 uiNumBytesRead = 0;
CHAR8 zName[32];
//OPEN FILE
HWFILE hfile = FileOpen( "BINARYDATA\\JA2SET.DAT", FILE_ACCESS_READ, FALSE );
SGP_THROW_IFFALSE(hfile, L"Cannot open tileset data file" );
XMLWriter xmlw;
xmlw.openNode("JA2SET");
// READ # TILESETS and compare
UINT8 numSets = 0;
FileRead( hfile, &numSets, sizeof( numSets ), &uiNumBytesRead );
// CHECK
SGP_THROW_IFFALSE( numSets <= MAX_TILESETS, L"Too many tilesets in the data file" );
xmlw.addAttributeToNextValue("numTilesets",(int)numSets);
// READ #files
UINT32 numFiles;
FileRead( hfile, &numFiles, sizeof( numFiles ), &uiNumBytesRead );
// COMPARE
SGP_THROW_IFFALSE( numFiles == NUMBEROFTILETYPES,
L"Number of tilesets slots in code does not match data file" );
xmlw.addAttributeToNextValue("numFiles",(int)numFiles);
xmlw.openNode("tilesets");
// Loop through each tileset, load name then files
for ( UINT8 cnt = 0; cnt < numSets; cnt++ )
{
xmlw.addAttributeToNextValue("index",(int)cnt);
xmlw.openNode("Tileset");
//Read name
FileRead( hfile, &zName, sizeof( zName ), &uiNumBytesRead );
xmlw.addValue("Name",std::string(zName));
// Read ambience value
UINT8 ambientID = 0;
FileRead( hfile, &ambientID, sizeof( UINT8 ), &uiNumBytesRead );
xmlw.addValue("AmbientID",(int)ambientID);
xmlw.openNode("Files");
// Loop for files
for ( UINT32 cnt2 = 0; cnt2 < numFiles; cnt2++ )
{
// Read file name
FileRead( hfile, &zName, sizeof( zName ), &uiNumBytesRead );
if(!std::string(zName).empty())
{
xmlw.addAttributeToNextValue("index",(int)cnt2);
xmlw.addValue("file",std::string(zName));
}
// Set into database
strcpy( gTilesets[ cnt ].TileSurfaceFilenames[ cnt2 ], zName );
//ddd{ добавляем в индекс 250 файл окоп.
// if((cnt==0)&&(cnt2+1 == uiNumFiles))
// { strcpy( gTilesets[ cnt ].TileSurfaceFilenames[ 151 ], "okop.sti" );
// xmlw.AddAttributeToNextValue("index",(int)151); //for exp in xml
// xmlw.AddValue("file",std::string("okop.sti"));
// }
//ddd}
}
xmlw.closeNode(); // Files
xmlw.closeNode(); // tileset
}
xmlw.closeNode();
FileClose( hfile );
xmlw.closeNode();
xmlw.writeToFile(filename);
}
#endif
void SetTilesetOneTerrainValues( )
{
// FIRST TEXUTRES
gTileSurfaceArray[ FIRSTTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ SECONDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ THIRDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FOURTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FIFTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SIXTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SEVENTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ REGWATERTEXTURE ]->ubTerrainID = LOW_WATER;
gTileSurfaceArray[ DEEPWATERTEXTURE ]->ubTerrainID = DEEP_WATER;
// NOW ROADS
gTileSurfaceArray[ FIRSTROAD ]->ubTerrainID = DIRT_ROAD;
gTileSurfaceArray[ ROADPIECES ]->ubTerrainID = DIRT_ROAD;
// NOW FLOORS
gTileSurfaceArray[ FIRSTFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ SECONDFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ THIRDFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ FOURTHFLOOR ]->ubTerrainID = FLAT_FLOOR;
// NOW ANY TERRAIN MODIFYING DEBRIS
}
void SetTilesetTwoTerrainValues( )
{
// FIRST TEXUTRES
gTileSurfaceArray[ FIRSTTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ SECONDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ THIRDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FOURTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FIFTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SIXTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SEVENTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ REGWATERTEXTURE ]->ubTerrainID = LOW_WATER;
gTileSurfaceArray[ DEEPWATERTEXTURE ]->ubTerrainID = DEEP_WATER;
// NOW ROADS
gTileSurfaceArray[ FIRSTROAD ]->ubTerrainID = DIRT_ROAD;
gTileSurfaceArray[ ROADPIECES ]->ubTerrainID = DIRT_ROAD;
// NOW FLOORS
gTileSurfaceArray[ FIRSTFLOOR ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ SECONDFLOOR ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ THIRDFLOOR ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FOURTHFLOOR ]->ubTerrainID = FLAT_GROUND;
}
void SetTilesetThreeTerrainValues( )
{
// DIFFERENCE FROM #1 IS THAT ROADS ARE PAVED
// FIRST TEXUTRES
gTileSurfaceArray[ FIRSTTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ SECONDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ THIRDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FOURTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FIFTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SIXTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SEVENTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ REGWATERTEXTURE ]->ubTerrainID = LOW_WATER;
gTileSurfaceArray[ DEEPWATERTEXTURE ]->ubTerrainID = DEEP_WATER;
// NOW ROADS
gTileSurfaceArray[ FIRSTROAD ]->ubTerrainID = PAVED_ROAD;
gTileSurfaceArray[ ROADPIECES ]->ubTerrainID = PAVED_ROAD;
// NOW FLOORS
gTileSurfaceArray[ FIRSTFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ SECONDFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ THIRDFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ FOURTHFLOOR ]->ubTerrainID = FLAT_FLOOR;
// NOW ANY TERRAIN MODIFYING DEBRIS
}
void SetTilesetFourTerrainValues( )
{
// DIFFERENCE FROM #1 IS THAT FLOOR2 IS NOT FLAT_FLOOR BUT FLAT_GROUND
// FIRST TEXUTRES
gTileSurfaceArray[ FIRSTTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ SECONDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ THIRDTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FOURTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ FIFTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SIXTHTEXTURE ]->ubTerrainID = LOW_GRASS;
gTileSurfaceArray[ SEVENTHTEXTURE ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ REGWATERTEXTURE ]->ubTerrainID = LOW_WATER;
gTileSurfaceArray[ DEEPWATERTEXTURE ]->ubTerrainID = DEEP_WATER;
// NOW ROADS
gTileSurfaceArray[ FIRSTROAD ]->ubTerrainID = DIRT_ROAD;
gTileSurfaceArray[ ROADPIECES ]->ubTerrainID = DIRT_ROAD;
// NOW FLOORS
gTileSurfaceArray[ FIRSTFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ SECONDFLOOR ]->ubTerrainID = FLAT_GROUND;
gTileSurfaceArray[ THIRDFLOOR ]->ubTerrainID = FLAT_FLOOR;
gTileSurfaceArray[ FOURTHFLOOR ]->ubTerrainID = FLAT_FLOOR;
// NOW ANY TERRAIN MODIFYING DEBRIS
}
| [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
] | [
[
[
1,
345
]
]
] |
15311698a9da97ef63debf17a48db28c57ec1b12 | 960a896c95a759a41a957d0e7dbd809b5929c999 | /Editor/level.cpp | e10198a79c82ce87d490c5d75f4c486c8bb2f929 | [] | no_license | WSPSNIPER/dangerwave | 8cbd67a02eb45563414eaf9ecec779cc1a7f09d5 | 51af1171880104aa823f6ef8795a2f0b85b460d8 | refs/heads/master | 2016-08-12T09:50:00.996204 | 2010-08-24T22:55:52 | 2010-08-24T22:55:52 | 48,472,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,605 | cpp | #include"headers.hpp"
#include"level.hpp"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <fstream>
Config::Config(string file)
{
File = file;
string temp;
ifstream config;
config.open( file.c_str() );
if(!config.bad())
{
while(config>>temp)
{
if(temp == "Map_x")
{
config>>x;
}
if(temp == "Map_y")
{
config>>y;
}
}
}
config.close();
}
void Level::SetFlag(int f)
{
for(int a = 0; a < z; a++)
{
for(int b = 0; b < x; b++)
{
for(int c = 0; c < y; c++)
{
tile[a][b][c].flag = f;
}
}
}
}
void Level::Create_Tiles(int X, int Y, int Z)
{
layer = -1;
x = X;
y = Y;
z = Z;
Clear_Tiles();
}
Level::~Level()
{
// delete [] tile; // dont delete it unless its a pointer on the heap!!!!!
}
void Level::Clear_Tiles()
{
cout<<"Clearinng tiles"<<endl;
int counter = 1;
for(int a = 0; a < z; a++)
{
for(int b = 0; b < x; b++)
{
for(int c = 0; c < y; c++)
{
tile[a][b][c].x = b * 32;
tile[a][b][c].y = c * 32;
tile[a][b][c].s_x = a * 32;
tile[a][b][c].s_y = 0;
tile[a][b][c].h = 32;
tile[a][b][c].w = 32;
tile[a][b][c].flag = 0;
counter++;
}
}
}
}
void Level::Save_Map(std::string buffer, int H, int W)
{
cout<<"Is something wrong?"<<endl<<"converted sfml to string: "<<buffer<<endl;
#ifndef Debug
cout<<"buffer: "<< buffer <<endl;
#endif
#ifdef Debug
cout<<"debug mode. Please Enter Filename: "<<endl;
cin>>buffer;
cin.ignore();
#endif
ofstream Save;
Save.open(buffer.c_str());
if(Save.good())
{
cout<<"Saving to: "<< buffer <<" Length: "<<buffer.size()<<endl;
cout<<"File being created..."<<endl;
Save<<"H "<< H <<" W "<< W <<"\n\n";
Save<<"MapX "<< x <<" MapY "<< y<<"\n\n";
for(int a = 0; a < z; a++)
{
for(int b = 0; b < x; b++)
{
for(int c = 0; c < y; c++)
{
Save<<"Layer "<< a << " Tile "<< c;
Save<<" X "<< tile[a][b][c].x <<" Y " << tile[a][b][c].y;
Save<<" Strip_x "<< tile[a][b][c].s_x;
Save<<" Strip_y "<<tile[a][b][c].s_y;
Save<<" Hieght "<< H;
Save<<" Width "<< W;
Save<<" Flag "<< tile[a][b][c].flag;
Save<<" END \n\n";
}
Save<<"\n";
}
Save<<"\n \n \n";
}
cout<<"done."<<endl;
cout << "file is good" << endl;
}
else
{
cout<<"File: "<< buffer<<" could not be created!"<<endl;
}
Save.flush(); // just make sure everything is written
Save.close();
}
void Level::Load_Map(std::string buffer)
{
string temp;
int flag;
#ifndef Debug
ifstream Load( buffer.c_str() );
#endif
#ifdef Debug
cout<<"debug mode. Please Enter Filename: "<<endl;
cin>>buffer;
cin.ignore();
ifstream Load( buffer.c_str() );
#endif
if(Load.is_open())
{
cout<<"Found file"<<endl;
while(Load>>temp)
{
if(temp == "MapX")
{
Load>>x;
}
if(temp == "MapY")
{
Load>>y;
}
if(temp == "Layer")
{
Load>>layer;
}
if(temp == "Tile")
{
Load>>tile_count;
}
if(temp == "Flag")
{
Load>>flag;
}
if(temp == "X")
{
Load>>x_coord;
}
if(temp == "Y")
{
Load>>y_coord;
}
if(temp == "Strip_x")
{
Load>>strip_x;
}
if(temp == "Strip_y")
{
Load>>strip_y;
}
if(temp == "H")
{
Load>>h;
}
if(temp == "W")
{
Load>>w;
}
if(temp == "END")
{
tile[layer][x_coord / w][y_coord / h].x = x_coord;
tile[layer][x_coord / w][y_coord / h].y = y_coord;
tile[layer][x_coord / w][y_coord / h].s_x = strip_x;
tile[layer][x_coord / w][y_coord / h].s_y = strip_y;
tile[layer][x_coord / w][y_coord / h].h = h;
tile[layer][x_coord / w][y_coord / h].w = w;
tile[layer][x_coord / w][y_coord / h].flag = flag;
}
}
}
else
{
cout<<"Could not open or find file: "<< buffer <<endl;
}
Load.close();
}
void Level::Draw(sf::Image &image, sf::RenderWindow &Window)
{
draw.SetImage( image );
if(layer == -1)
{
for(int a = 0; a < z; a++)
{
for(int b = 0; b < x; b++)
{
for(int c = 0; c < y; c++)
{
if(tile[a][b][c].rendered)
{
draw.SetSubRect( sf::IntRect(tile[a][b][c].s_x,tile[a][b][c].s_y,
tile[a][b][c].s_x + tile[a][b][c].w,
tile[a][b][c].s_y + tile[a][b][c].h) );
draw.SetPosition(tile[a][b][c].x + ofs_x, tile[a][b][c].y + ofs_y);
Window.Draw(draw);
}
}
}
}
}
else
{
for(int d = 0; d < x; d++)
{
for(int e = 0; e < y; e++)
{
draw.SetSubRect( sf::IntRect(tile[layer][d][e].s_x,tile[layer][d][e].s_y, tile[layer][d][e].s_x + tile[layer][d][e].w, tile[layer][d][e].s_y + tile[layer][d][e].h) );
draw.SetPosition(tile[layer][d][e].x + ofs_x, tile[layer][d][e].y + ofs_y);
Window.Draw(draw);
}
}
}
}
| [
"michaelbond2008@e78017d1-81bd-e181-eab4-ba4b7880cff6",
"lukefangel@e78017d1-81bd-e181-eab4-ba4b7880cff6"
] | [
[
[
1,
3
],
[
8,
33
],
[
47,
59
],
[
61,
79
],
[
81,
86
],
[
88,
89
],
[
91,
101
],
[
105,
107
],
[
110,
126
],
[
128,
134
],
[
136,
140
],
[
142,
145
],
[
147,
149
],
[
151,
183
],
[
188,
219
],
[
222,
243
],
[
252,
268
]
],
[
[
4,
7
],
[
34,
46
],
[
60,
60
],
[
80,
80
],
[
87,
87
],
[
90,
90
],
[
102,
104
],
[
108,
109
],
[
127,
127
],
[
135,
135
],
[
141,
141
],
[
146,
146
],
[
150,
150
],
[
184,
187
],
[
220,
221
],
[
244,
251
]
]
] |
8c66b7dcdfa9d06facf0e36e98b1ee7db350c56b | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Interface/WndRankWar.h | cd727aeafbd1131c1bb8a5d564359d1219bef3ca | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 3,574 | h | #ifndef __WNDRANKWAR__H
#define __WNDRANKWAR__H
class CWndRankWarTabGiveUp : public CWndNeuz
{
public:
CWndRankWarTabGiveUp();
~CWndRankWarTabGiveUp();
int m_nCurrentList; // 출력될 멤버리스트의 시작 인덱스.
int m_nMxOld, m_nMyOld; // 과거 좌표.
virtual BOOL OnMouseWheel( UINT nFlags, short zDelta, CPoint pt );
virtual void OnMouseMove(UINT nFlags, CPoint point );
virtual void OnRButtonDown( UINT nFlags, CPoint point );
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
};
class CWndRankWarTabLose : public CWndNeuz
{
public:
CWndRankWarTabLose();
~CWndRankWarTabLose();
int m_nCurrentList; // 출력될 멤버리스트의 시작 인덱스.
// int m_nSelect;
int m_nMxOld, m_nMyOld; // 과거 좌표.
virtual BOOL OnMouseWheel( UINT nFlags, short zDelta, CPoint pt );
virtual void OnMouseMove(UINT nFlags, CPoint point );
virtual void OnRButtonDown( UINT nFlags, CPoint point );
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
};
class CWndRankWarTabWin : public CWndNeuz
{
public:
CWndRankWarTabWin();
~CWndRankWarTabWin();
int m_nCurrentList; // 출력될 멤버리스트의 시작 인덱스.
// int m_nSelect;
int m_nMxOld, m_nMyOld; // 과거 좌표.
virtual BOOL OnMouseWheel( UINT nFlags, short zDelta, CPoint pt );
virtual void OnMouseMove(UINT nFlags, CPoint point );
virtual void OnRButtonDown( UINT nFlags, CPoint point );
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
};
class CWndRankWar : public CWndNeuz
{
public:
CWndRankWar();
~CWndRankWar();
CWndRankWarTabGiveUp m_WndRankWarTabGiveUp;
CWndRankWarTabLose m_WndRankWarTabLose;
CWndRankWarTabWin m_WndRankWarTabWin;
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
};
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
94
]
]
] |
ae5030160cd03812e02625785dfbdbd6409e502d | 30e4267e1a7fe172118bf26252aa2eb92b97a460 | /code/pkg_UnitTest/Modules/TestCore/TestLogging.h | 8efc2d000888e828f167f49dd6a35ee94ccdff6b | [
"Apache-2.0"
] | permissive | thinkhy/x3c_extension | f299103002715365160c274314f02171ca9d9d97 | 8a31deb466df5d487561db0fbacb753a0873a19c | refs/heads/master | 2020-04-22T22:02:44.934037 | 2011-01-07T06:20:28 | 2011-01-07T06:20:28 | 1,234,211 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,248 | h | // Copyright 2008-2011 Zhang Yun Gui, [email protected]
// https://sourceforge.net/projects/x3c/
//
// 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.
#pragma once
#include "BaseTest.h"
class TestLogging : public BaseTest
{
CPPUNIT_TEST_SUITE( TestLogging );
CPPUNIT_TEST( testAllMacros );
CPPUNIT_TEST( testAllMacrosWithID );
CPPUNIT_TEST( testMultiTypes );
CPPUNIT_TEST( testIdFormat );
CPPUNIT_TEST( testGroup );
CPPUNIT_TEST( testObserver );
CPPUNIT_TEST_SUITE_END();
public:
TestLogging();
virtual void setUp();
virtual void tearDown();
void testAllMacros();
void testAllMacrosWithID();
void testMultiTypes();
void testIdFormat();
void testGroup();
void testObserver();
};
| [
"rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3"
] | [
[
[
1,
43
]
]
] |
f1590e87c62133f89f2564af5c46e547db4253f6 | 81a3611bfa4e9022e1194295a8f314bafa744f69 | /HGRASS/src/grass/src/ToGraph.cpp | e2cf398607d2d66ab36a3fccd63c14a8fefc9348 | [] | no_license | ominux/sjtuedaacgrass | 65c02f6a1db52e8194157fd1622b73124220a27c | 463b1926b1eddcc06ff2253b3077aad1bca7e37b | refs/heads/master | 2016-09-15T16:14:00.747072 | 2010-05-18T13:20:08 | 2010-05-18T13:20:08 | 32,243,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,439 | cpp | /** ToGraph.cpp
* Parsing a standard netlist to a graph file.
* G.Shi, 03-25-04, 03-31-04
*
* Cautions of this code:
* (1) Multiple dependent sources:
* - The case of one edge controlled by multiple edges can be
* treated by splitting the controlled edge into multiple ones
* (in series or parallel depending on CS/VS).
* - The case of one edge controlling multiple edges can be
* handeled, but for internal representation during parsing
* a list is needed for such a controlling edge. This is NOT
* implemented at the moment.
* (2)
*
*/
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <cstdio>
#include "ToGraph.h"
using std::cout;
using std::endl;
using std::cerr;
using std::printf;
extern int read_input(const char *filename);
// Defined in "netgram.g" and duplicated in "netgram.cpp".
//using namespace std;
ToGraph::ToGraph()
{
printf("ToGraph(): this = %p\n", this);
E = 0;
M = 0;
N = 0;
Nsrc = Nout = 0;
extra_nn = 0;
edge_list = cur_edge = NULL;
mos_list = cur_mos = NULL;
src_edge = out_edge = NULL;
node_list = node_tail = NULL;
}
ToGraph::~ToGraph()
{
printf("~ToGraph(): this = %p\n", this);
// Release the list of edges created.
while (edge_list)
{
cur_edge = edge_list;
edge_list = edge_list->next;
delete cur_edge;
}
// Release the list of mosfets created
/*while (mos_list)
{
cur_mos = mos_list;
mos_list = mos_list->next;
delete cur_mos;
}*/
// Release the list of nodes created.
while (node_list)
{
Node_g *node = node_list;
node_list = node_list->next;
delete node;
}
}
void
ToGraph::readNetlist(const char *filename)
{
#ifdef TRACE
cout << "\nIn readNetlist() ";
#endif
cout << "\n->Start parsing the netlist ... \n";
// Call the parser.
if (read_input(filename) == -1)
{
cerr << "\nMake sure the netlist file exists.";
exit(1);
}
// read_input() defined in the grammar file "netgram.g".
cout << "\n->Finished parsing the netlist." << endl;
// Check the number of input/output.
if (Nsrc != 1 || Nout != 1)
{
cout << "\nWarning: Something wrong with input and output."
<< "\nMake sure there are only one input and one output "
<< "in the original netlist."
<< endl;
exit(1);
}
//calMosfetModelParameters();
// IMPORTANT!
// Must renumber the node_list. It also counts the # of nodes.
renumber_nodes();
}
// Write the edge list to a graph file.
void
ToGraph::writeGraph(const char *filename)
{
#ifdef TRACE
cout << "\nIn writeGraph() ";
#endif
// Before writing the graph file, check whether the edge_list
// and the node_list have been created.
if (!edge_list || !node_list)
{
cerr << "\nNo edges or nodes. writeGraph() aborted.";
return;
}
outFile.open(filename);
if (outFile.fail())
{
cerr << "\nCan't open file: " << filename << endl;
exit(1);
}
outFile << title << endl;
outFile << "E = " << E << ", N = " << N << endl;
// Nodes counted from 0.
Edge_g *edge;
for(edge = edge_list; edge; edge = edge->next)
{
outFile << ToUpper(edge->name) << " "
<< edge->node1->num << " " << edge->node2->num << " ";
// Make sure that the pairing edge names are all set.
if ( (edge->type >= CC) && (edge->pname == NULL) )
{
cerr << "\nThe name for one pairing edge is missing.";
}
switch (edge->type)
{
case Z:
outFile << "Z " << edge->value;
break;
case Y:
outFile << "Y " << edge->value;
break;
case VS:
outFile << "VS " << ToUpper(edge->pname)
<< " " << edge->value;
break;
case CS:
outFile << "CS " << ToUpper(edge->pname)
<< " " << edge->value;
break;
case VC:
outFile << "VC" << " " << ToUpper(edge->pname);
break;
case CC:
outFile << "CC" << " " << ToUpper(edge->pname);
break;
default:
break;
}
outFile << endl;
}
outFile.close();
cout << "\n->A graph file has been created: \"" << filename << "\"";
}
void
ToGraph::parseRLC(char *name, char *n1, char *n2,
char *value, char *var_name)
{
#ifdef TRACE
cout << "\nIn parseRLC()" << flush;
#endif
// Check whether the branch is a duplicate.
if ( query_edge(name) )
{
cout << "\nBranch [" << name << "] is a duplicate, skipped.";
return;
}
// Process the nodes
int nn1 = atoi(n1);
int nn2 = atoi(n2);
Node_g *node1, *node2;
//cout << "\n nn1 = " << nn1 << ", nn2 = " << nn2;
node1 = query_node(nn1);
if ( !node1 )
{
node1 = new Node_g;
node1->num = nn1;
node1->next = NULL;
add_node(node1);
}
node2 = query_node(nn2);
if ( !node2 )
{
node2 = new Node_g;
node2->num = nn2;
node2->next = NULL;
add_node(node2);
}
Edge_g *edge = new Edge_g;
if (!edge)
{
cerr << "\nMemory allocation error for an RLC edge.\n";
exit(1);
}
edge->name = CopyStr(name);
edge->node1 = node1;
edge->node2 = node2;
edge->value = TransValue(value);
edge->pname = NULL;
edge->var_name = CopyStr(var_name);
edge->next = NULL;
// Check the element type.
switch ( tolower(edge->name[0]) )
{
case 'r':
case 'l':
edge->type = Z;
break;
case 'c':
edge->type = Y;
break;
default:
break;
}
char* tmpName = strdup(edge->name);
char* tmp = NULL;
while(tmpName)
tmp = strsep(&tmpName,"_");
if(tmp && strcmp(tmp,edge->name))
{
Mosfet* pMos = query_mosfet(tmp);
if(pMos) edge->pMosfet = pMos;
}
free(tmpName);
add_edge( edge );
} // parseRLC()
// parseSRC()
// parses an independent input source.
// Note:
// (1) By the standard netlist format, a Voltage Source (Vname) is used for
// a CC branch.
// (2) We assume an independent V-SRC will not be used for CC.
// (3) We assume a V-SRC used for CC always has a value of 0 volt.
// (4) The two edges representing input and output are specifically
// added to the beginning of the edge list so that they are sorted
// with the highest order (index) for using DDD.
void
ToGraph::parseSRC(char *name, char *n1, char *n2,
char *dc_val, char *ac_val)
{
#ifdef TRACE
cout << "\nIn parseSRC()" << flush;
#endif
int CC_edge = 0; // Flag for a CC_edge.
// Check whether the branch is a duplicate.
if ( query_edge(name) )
{
cout << "\nBranch [" << name << "] already parsed, hence skipped.";
return;
}
if (Nsrc == 1)
{
cout << "\nWarning: ";
cout << "Only one indep source allowed; this one is ignored.";
return;
}
// Process the nodes
int nn1 = atoi(n1);
int nn2 = atoi(n2);
Node_g *node1, *node2;
node1 = query_node(nn1);
if ( !node1 )
{
node1 = new Node_g;
node1->num = nn1;
node1->next = NULL;
add_node(node1);
}
node2 = query_node(nn2);
if ( !node2 )
{
node2 = new Node_g;
node2->num = nn2;
node2->next = NULL;
add_node(node2);
}
Edge_g *edge = new Edge_g;
if (!edge)
{
cerr << "\nMemory allocation error for a source edge.\n";
exit(1);
}
edge->node1 = node1;
edge->node2 = node2;
// Check whether it is a Current Controlling (CC) edge.
if (dc_val)
{
edge->value = TransValue(dc_val);
if (edge->value == 0) CC_edge = 1;
}
else if (ac_val)
{
edge->value = TransValue(ac_val);
if (edge->value == 0) CC_edge = 1;
}
else
edge->value = 0.0;
edge->pname = NULL;
edge->var_name = NULL;
edge->next = NULL;
// Check the edge type.
if (!CC_edge)
{
edge->name = CopyStr(name);
switch ( tolower(edge->name[0]) )
{
case 'v':
edge->type = VS;
break;
case 'i':
edge->type = CS;
break;
default:
break;
}
// Let src_edge point to this edge.
src_edge = edge; // Only one source allowed now.
// Check whether the out_edge is available.
if ( out_edge )
{
// Establish the pairing of edges.
src_edge->pname = out_edge->name;
out_edge->pname = src_edge->name;
}
++Nsrc;
}
else // A CC edge
{
// Modify the edge name with a preceding "I".
char* cc_name = new char[strlen(name)+2];
sprintf(cc_name, "I%s", name);
//cout << "\n name = " << name;
edge->name = CopyStr(cc_name);
//cout << "\n edge->name = " << edge->name;
edge->type = CC;
// Query another edge controlled by this edge.
Edge_g *xs_edge = query_pair(edge->name);
// If the XS edge exists, assign a pairing name to it.
if (xs_edge)
{
xs_edge->pname = edge->name;
edge->pname = xs_edge->name;
}
else
edge->pname = NULL; // the pairing edge not parsed yet.
delete[] cc_name;
}
// Add the indep src edge at the head of edge list.
add_edge_at_head( edge );
} // parseSRC()
// parseOUT()
// parses the output control meanwhile creates an output edge.
// Note:
// (1) If the output is a voltage, then add a new edge IN PARALLEL to
// the output element.
// (2) If the output is a current, then add a new edge IN SERIES to
// the output element. In this case, an extra node has to be added
// (extra_nn, a negative number in this implementation).
// Also, in this case the string <br_name> is the name of the branch
// from which the output current is measured.
void
ToGraph::parseOUT(char *name, char *n1, char *n2, char *br_name)
{
#ifdef TRACE
cout << "\nIn parseOUT()" << flush;
#endif
// Make a name for output edge.
char out_name[10];
sprintf(out_name, "%co", name[0]);
// Check whether the name is alreay used.
if ( query_edge(out_name) )
{
cout << "\nBranch [" << name << "] already parsed -- skipped.";
return;
}
if (Nout == 1)
{
cout << "\nWarning: ";
cout << "-- Outputs except the first one are ignored.";
return;
}
// Make an extra edge.
Edge_g *edge = new Edge_g;
if (!edge)
{
cerr << "\nMemory allocation error for an output edge.\n";
exit(1);
}
if (tolower(name[0]) == 'v')
{
// Process an output of voltage.
int nn1 = atoi(n1);
int nn2 = (n2 == NULL? 0 : atoi(n2));
Node_g *node1, *node2;
node1 = query_node(nn1);
if ( !node1 )
{
node1 = new Node_g;
node1->num = nn1;
node1->next = NULL;
add_node(node1);
}
node2 = query_node(nn2);
if ( !node2 )
{
node2 = new Node_g;
node2->num = nn2;
node2->next = NULL;
add_node(node2);
}
// Assign to the extra edge for the voltage output.
edge->name = CopyStr(out_name);
edge->node1 = node1;
edge->node2 = node2;
edge->value = 0.0;
edge->pname = NULL;
edge->var_name = NULL;
edge->next = NULL;
edge->type = VC;
}
else if (tolower(name[0]) == 'i')
{
// Process an output of current.
// First get the branch name that the current flows.
//cout << "\nOutput branch : " << br_name;
Edge_g *edge0 = query_edge(br_name);
if (!edge0)
{
cerr << "\nThe branch for current (I) output is unknown."
<< "\nCheck the netlist.";
exit(1);
}
// Get the node nums of the output branch.
Node_g *node2 = edge0->node2;
// Make a new node for an extra current edge in series.
Node_g *node0 = new Node_g;
node0->num = --extra_nn; // -1, -2, ...
node0->next = NULL;
add_node(node0);
// Modify edge0->node2 to node0
// (node1) ------ (node0) ------ (node2)
edge0->node2 = node0;
// Assign to the extra edge for the current output.
edge->name = CopyStr(out_name);
edge->node1 = node0;
edge->node2 = node2;
edge->value = 0.0;
edge->pname = NULL;
edge->var_name = NULL;
edge->next = NULL;
edge->type = CC;
}
// Let out_edge point to this edge.
out_edge = edge; // Only one output allowed now.
// Check whether a src_edge is already parsed.
if ( src_edge )
{
// Establish the pairing of edges.
out_edge->pname = src_edge->name;
src_edge->pname = out_edge->name;
}
// Add the output edge at the head of edge list.
add_edge_at_head( edge );
++Nout;
} // parseOUT()
// parseVCXS()
// parses a VCCS/VCVS branch. Because parsing a VCCS is very similar to
// parsing a VCVS branch, they can be parsed by the same function.
// Note:
// (1) For tree enumeration analysis, an extra edge is added to the
// graph for the controlling 'VC' branch, although in the circuit
// an element branch can be used as a VC branch.
// (2) Since we assume only one independent source, the VC edge should
// not be an independent voltage source. An independe source is
// parsed separately by parseSRC().
// (3) Two edges (CS/VS, VC) will be added to the graph after parsing
// a VCXS branch.
//
void
ToGraph::parseVCXS(char *name, char *n1, char *n2, char *nc1, char *nc2,
char *value, char *var_name)
{
#ifdef TRACE0
cout << "\nIn parseVCXS()" << flush;
#endif
// Check whether the branch is a duplicate.
if ( query_edge(name) )
{
cout << "\nBranch [" << name << "] already parsed -- skipped.";
return;
}
int nn[4];
Node_g *node[4];
nn[0] = atoi(n1); nn[1] = atoi(n2);
nn[2] = atoi(nc1); nn[3] = atoi(nc2);
// Spice netlist allows the controlling and controlled edges are the
// same edge. This is normally used for a conductance/admittance (G).
if ( (nn[0] == nn[2] && nn[1] == nn[3]) ||
(nn[0] == nn[3] && nn[1] == nn[2]) )
{
cout << "\nA G-edge in VCCS form.";
for (int i = 0; i < 2; i++)
{
node[i] = query_node(nn[i]);
if ( !node[i] )
{
node[i] = new Node_g;
node[i]->num = nn[i];
node[i]->next = NULL;
add_node(node[i]);
}
}
Edge_g *edge = new Edge_g;
if (!edge)
{
cerr << "\nMemory allocation error for a G-edge.\n";
exit(1);
}
edge->name = CopyStr(name);
edge->node1 = node[0];
edge->node2 = node[1];
if (nn[0] == nn[2])
edge->value = TransValue(value);
else
edge->value = -TransValue(value);
edge->pname = NULL;
edge->var_name = CopyStr(var_name);
edge->next = NULL;
edge->type = Y;
add_edge( edge );
return;
}
// Process the nodes of two distinct edges.
for (int i = 0; i < 4; i++)
{
node[i] = query_node(nn[i]);
if ( !node[i] )
{
node[i] = new Node_g;
node[i]->num = nn[i];
node[i]->next = NULL;
add_node(node[i]);
}
}
Edge_g *edge1 = new Edge_g; // for the CS/VS edge
if (!edge1)
{
cerr << "\nMemory allocation error for edge in parseVCCS().\n";
exit(1);
}
edge1->name = CopyStr(name);
edge1->node1 = node[0];
edge1->node2 = node[1];
edge1->value = TransValue(value);
edge1->pname = NULL;
edge1->var_name = NULL;
edge1->next = NULL;
// Check the element type.
switch ( tolower(edge1->name[0]) )
{
case 'e':
edge1->type = VS; // VCVS
break;
case 'g':
edge1->type = CS; // VCCS
break;
default:
break;
}
// Make a name for the (extra) VC edge
char* vc_name = new char[strlen(name)+2];
sprintf(vc_name, "V%s", name);
edge1->pname = CopyStr(vc_name); // name of the controlling edge
char* tmpName = strdup(edge1->name);
char* tmp = NULL;
while(tmpName)
tmp = strsep(&tmpName,"_");
if(tmp && strcmp(tmp,edge1->name))
{
Mosfet* pMos = query_mosfet(tmp);
if(pMos) edge1->pMosfet = pMos;
}
free(tmpName);
add_edge( edge1 );
Edge_g *edge2 = new Edge_g; // Allocate another edge for VC.
if (!edge2)
{
cerr << "\nMemory allocation error for edge in parseVCCS().\n";
exit(1);
}
edge2->name = edge1->pname; // name of the controlling edge
edge2->node1 = node[2];
edge2->node2 = node[3];
edge2->value = 0.0;
edge2->pname = edge1->name; // name of the controlled edge
edge2->var_name = NULL;
edge2->next = NULL;
edge2->type = VC;
add_edge( edge2 );
delete[] vc_name;
return;
} // parseVCXS()
// parseCCXS()
// parses a CCCS/CCVS branch.
// Note:
// (1) According to standard netlist format, the Controlling Current (CC)
// is always a current flowing through a Voltage Source (noted by Vname).
// (2) It might be easier for coding by requiring that a CC branch
// always precede a branch controlled by it in the netlist.
// But I think by relaxing this requirement it should give more freedom
// to the netlist. This implementation does not require such precedence.
void
ToGraph::parseCCXS(char *name, char *n1, char *n2, char *Vname,
char *value, char *var_name)
{
#ifdef TRACE0
cout << "\nIn parseCCXS()" << flush;
#endif
// Check whether the branch is a duplicate.
if ( query_edge(name) )
{
cout << "\nBranch [" << name << "] already parsed -- skipped.";
return;
}
int nn[2];
Node_g *node[2];
nn[0] = atoi(n1); nn[1] = atoi(n2);
for (int i = 0; i < 2; i++)
{
node[i] = query_node(nn[i]);
if ( !node[i] )
{
node[i] = new Node_g;
node[i]->num = nn[i];
node[i]->next = NULL;
add_node(node[i]);
}
}
// Make a name for the CC edge from "Vname".
char *cc_name = new char[strlen(Vname)+2];
sprintf(cc_name, "I%s", Vname);
Edge_g *edge1 = new Edge_g; // for CS edge
if (!edge1)
{
cerr << "\nMemory allocation error for edge in parseCCXS().\n";
exit(1);
}
edge1->name = CopyStr(name);
edge1->node1 = node[0];
edge1->node2 = node[1];
edge1->value = TransValue(value);
edge1->pname = CopyStr(cc_name);
edge1->var_name = NULL;
edge1->next = NULL;
// Check the controlled edge type.
switch ( tolower(edge1->name[0]) )
{
case 'f':
edge1->type = CS; // CCCS
break;
case 'h':
edge1->type = VS; // CCVS
break;
default:
break;
}
char* tmpName = strdup(edge1->name);
char* tmp = NULL;
while(tmpName)
tmp = strsep(&tmpName,"_");
if(tmp && strcmp(tmp,edge1->name))
{
Mosfet* pMos = query_mosfet(tmp);
if(pMos) edge1->pMosfet = pMos;
}
free(tmpName);
add_edge( edge1 );
// Now query whether the CC (Vname) edge is already parsed.
// If it was parsed before this edge, then its pairing edge
// (controlled) hasn't been assigned.
// Warning: For the moment we assume one edge does not control
// multiple edges (to be extended.)
Edge_g *cc_edge = query_edge(edge1->pname);
if (cc_edge && !cc_edge->pname)
cc_edge->pname = edge1->name;
// Do not create the CC edge if not parsed yet!
// It will be created when it is parsed.
delete[] cc_name;
return;
} // parseCCXS()
void
ToGraph::parseMOSFET(char *name, char *nd, char *ng, char *ns, char *nb,
char *model, char *w, char *l)
{
printf("\nM%s nd=%s, ng=%s, ns=%s, nb=%s, model =%s, w=%s, l=%s",name,nd,ng,ns,nb,model,w,l);
/*int nn[4];
Node_g *node[4];
nn[0] = atoi(nd); nn[1] = atoi(ng);
nn[2] = atoi(ns); nn[3] = atoi(nb);
for (int i = 0; i < 4; i++)
{
node[i] = query_node(nn[i]);
if ( !node[i] )
{
node[i] = new Node_g;
node[i]->num = nn[i];
node[i]->next = NULL;
add_node(node[i]);
}
}*/
Mosfet* pMosfet = new Mosfet();
pMosfet->name = CopyStr(name);
pMosfet->noded = NULL;//node[0];
pMosfet->nodeg = NULL;//node[1];
pMosfet->nodes = NULL;//node[2];
pMosfet->nodeb = NULL;//node[3];
pMosfet->w = TransValue(w);
pMosfet->l = TransValue(l);
pMosfet->value = pMosfet->w/pMosfet->l;
bool isNMOS = true;
if(!strcmp(model,"nmos"))
pMosfet->type = NMOS_DEF;
else if(!strcmp(model,"nch3"))
pMosfet->type = NMOS_L3;
else if(!strcmp(model,"pmos"))
pMosfet->type = PMOS_DEF;
else if(!strcmp(model,"pch3"))
pMosfet->type = PMOS_L3;
else
pMosfet->type = MODEL_TYPE_UNKNOWN;
// Ma Diming ToDo:
// Create Model According to the different ModelType
pMosfet->pModel = new MosfetModelBsim3V3(pMosfet->type);
// End of ToDo Ma Diming
pMosfet->next = NULL;
add_mosfet(pMosfet);
}
//-------- the following are private methods --------------------------
// query_node()
// searches the node list to see whether
// the node is already there. If yes, it returns the pointer to this node.
Node_g *
ToGraph::query_node(int node_num)
{
//cout << "\nIn query_node() ";
Node_g *node = node_list;
for (; node; node = node->next)
if (node->num == node_num) return node;
return NULL;
}
// add_node()
// inserts a new node to the node list.
// The nodes are sorted in increasing node number. However,
// negative node numbers are always attached to the end of the list.
// Note that negative node numbers are used for those auxiliary nodes.
void
ToGraph::add_node(Node_g *node)
{
//cout << "\nIn add_node() ";
if (!node)
{
cerr << "\nNo node to add by add_node().";
return;
}
// Attach a negative-numbered node to the tail of the node_list.
if (node->num < 0)
{
if (!node_list)
node_list = node_tail = node;
else
node_tail->next = node, node_tail = node_tail->next;
return;
}
Node_g *pre_nd = NULL, *this_nd = node_list;
while ( this_nd && this_nd->num < node->num )
pre_nd = this_nd, this_nd = this_nd->next;
//cout << "\nAt " << __FILE__ << ": " << __LINE__;
// Proof of no repeated node.
if (this_nd && this_nd->num == node->num)
{
cerr << "\nAdding a duplicated node, ignored.";
return;
}
if (!node_list) // Empty list
node_list = node_tail = node;
else if (!pre_nd) // Add to the head
node->next = node_list, node_list = node;
else // Add to a place behind the head
pre_nd->next = node, node->next = this_nd;
// Update the tail if another node attached to the tail.
if (node_tail->next)
node_tail = node_tail->next;
}
// renumber_nodes()
// traverses the node_list, resets the node numbers continuously,
// and counts the nodes.
// After renumbering, the nodes are numbered continuously from 0,
// with node 0 the ground (datum).
//
// The reason to do this is that the netlist writer is allowed
// to use an arbitrary numbering scheme, except that the datum must
// be node 0 and no node is numbered negative.
void
ToGraph::renumber_nodes()
{
//cout << "\nIn renumber_nodes() ";
if (!node_list) return; // do nothing
int cnt = 0;
Node_g *node = node_list;
for (; node; node = node->next)
node->num = cnt++;
// Set the number of nodes
N = cnt;
}
// query_edge()
// searches the edge_list to see whether
// the edge is already there. If yes, it returns the pointer to this edge.
Edge_g *
ToGraph::query_edge(char *edge_name)
{
//cout << "\nIn query_edge() ";
if (!edge_name) return NULL;
Edge_g *edge = edge_list;
for (; edge; edge = edge->next)
if ( strcmp(edge->name, edge_name) == 0)
return edge;
return NULL;
}
// query_pair()
// queries the edge with the given pair_name.
// If yes, it returns the pointer to this edge.
Edge_g *
ToGraph::query_pair(char *pair_name)
{
//cout << "\nIn query_pair() for \"" << pair_name << "\"";
if (!pair_name) return NULL;
Edge_g *edge = edge_list;
for (; edge; edge = edge->next)
{
if (!edge->pname) continue;
if ( strcmp(edge->pname, pair_name) == 0)
return edge;
}
return NULL;
}
// add_edge()
// adds an edge to the edge_list. Always add the edge to the end
// pointed by cur_edge.
void
ToGraph::add_edge(Edge_g *edge)
{
//cout << "\nIn add_edge() ";
// Insert to edge_list
if ( !edge_list )
edge_list = cur_edge = edge;
else
cur_edge->next = edge, cur_edge = cur_edge->next;
++E;
}
// add_edge_at_head()
// adds an edge to the beginning of the edge_list.
void
ToGraph::add_edge_at_head(Edge_g *edge)
{
//cout << "\nIn add_edge_at_head() ";
// Insert to edge_list
if ( !edge_list )
edge_list = cur_edge = edge;
else
edge->next = edge_list, edge_list = edge;
++E;
}
void
ToGraph::add_mosfet(Mosfet* mosfet)
{
//cout << "\nIn add_mosfet() ";
// Insert to mos_list
if ( !mos_list )
mos_list = cur_mos = mosfet;
else
cur_mos->next = mosfet, cur_mos = cur_mos->next;
++M;
}
Mosfet *
ToGraph::query_mosfet(char* name)
{
//cout << "\nIn query_mosfet() ";
Mosfet* mList = mos_list;
for (; mList; mList = mList->next)
if (!strcmp((mList->name)+1,name)) return mList;
return NULL;
}
void
ToGraph::calMosfetModelParameters()
{
Mosfet* mList = mos_list;
for (; mList; mList = mList->next)
mList->calBasicModelParameters(mList);
}
| [
"wontian@ecd5914e-0e2d-11df-9afa-8babb764c599"
] | [
[
[
1,
1008
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.