SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
1
A simple and powerful
property system for C++
GCDC 2008
David Salz
david.salz@bitfield.de
2
• Bitfield
• small studio from Berlin, Germany
• founded in 2006
• developer for PC, DS, Wii
• focus on casual games for PC and DS
• advertising games for trade shows &
events
3
• Bitfield
• licensed DS middleware developer
• BitEngineDS, high level game engine
• used in 10 games so far
• adventure, jump‘n‘run, puzzle games, pet
simulation
• www.bitfield.de
4
• Games Academy
• founded in 2000
• based in Berlin and
Frankfurt/Main
• ~170 students
• Hire our students!
• Constantly looking for
teachers and
lecturers!
5
What is a Property System?
class CCar
{
Vec3 position;
DWORD color
float max_speed;
int ai_type;
...
* 3d model
* shader parameters
* sounds
etc.
...
};
location 127.3, 0, 14.0
max speed 120 km/h
color
AI Type Easy
Team 2
▼
▼
▲
...
3d model mini.x ...
6
Uses of Property Systems (1)
• a property system can be used for a lot of things!
• serialization
• store objects on disc (or stream over network)
• e.g. saved games, level file format, scene graph file format
• undo / redo
• figure out which properties were changed, store old value
• = selective serialization
• client / server synchronization
• send changed properties to client/server
• = selective serialization
7
Uses of Property Systems (2)
• a property system can be used for a lot of things!
• animation
• change property values over time
• e.g. animated GUIs, in-game cut-scenes
• integration of scripting languages
• automatically create „glue code“ to access object
properties from scripting languages
8
What do we want? (1)
• easy-to-use system
• lightweight
• cause as little performance and memory overhead as possible
• performance may not be an issue for editors...
• ...but may for serialization, animation, scripting languages
• type safe
• i.e. all C++ type safety and type conversion mechanisms should stay
intact
• non-intrusive
• i.e. it should not require modification of the class whose properties
are to be exposed
• it might by part of an external library; source code may not be available
9
What do we want? (2)
• support polymorphic objects
• i.e. work correctly with virtual functions
• be aware of C++ protection mechanisms
• i.e. not violate const, private or protected modifiers
• support real-time manipulation of objects with no
extra code
• i.e. the object should not need extra code to deal with a changed
property at runtime
10
Existing Solutions
• ... using data pointers
• ... using strings
• … using databases
• ... using reflection
• properties in Microsoft .NET
• ... using member function pointers
11
Data Pointers (1)
• „A Property Class for Generic C++ Member
Access“
• by Charles Cafrelli, published in Game Programming
Gems 2
• Idea:
• store a pointer to the data (inside to object)
• plus type information
• plus name
12
Data Pointers (2)
class Property
{
protected:
union Data
{
int* m_int;
float* m_float;
string* m_string;
bool* m_bool;
};
enum Type
{
INT,
FLOAT,
STRING,
BOOL,
EMPTY
};
Data m_data;
Type m_type;
string m_name;
Property(string const& name, int* value);
Property(string const& name, float* value);
Property(string const& name, string* value);
Property(string const& name, bool* value);
~Property ();
bool SetUnknownValue(string const& value);
bool Set(int value);
bool Set(float value);
bool Set(string const& value);
bool Set(bool value);
void SetName(string const& name);
string GetName() const;
int Getlnt();
float GetFloatf);
string GetString();
bool GetBool();
}
13
Data Pointers (3)
class PropertySet
{
protected:
HashTable<Property>m_properties;
public:
PropertySet();
virtual -PropertySet();
void Register(string const& name, int* value);
void Register(string const& name, float* value);
void Register(string const& name, string* value);
void Register(string const& name, bool* value);
// look up a property
Property* Lookup(string const& name);
// get a list of available properties
bool SetValue(string const& name, string* value);
bool Set(string const& name, string const& value);
bool Set(string const& name, int value);
bool Set(string const& name, float value);
bool Set(string const& name, bool value);
bool Set(string const& name, char* value);
};
class GameObj : public PropertySet
{
int m_test;
GameObj()
{
Register("test",&m_test);
}
};
Property* testprop =
aGameObj->Lookup("test");
int test_value =
testprop->GetInt();
14
Data Pointers (4)
• Problems:
• Is it a good idea to modify a (private?) variable
directly?
•  need to notify object after property change!
• objects carry unnecessary and redundant data
• every GameObj holds string names for all properties...
• ... and pointers to it’s own members!
• support for more types?
• could be done using templates
• or by storing data as string internally
15
String-Based Properties
• Idea:
• store all properties as strings
• convert from / to string as needed
• used by CEGui
• Crazy Eddie's GUI System; open source GUI
• used with OGRE / Irrlicht game engines
• used in several commercial games
16
17
• PropertyReceiver is just an empty class, used for type safety
• there is a derived class for every property of every class (181 !)
CEGUI::Property
d_name : String
d_help : String
d_default : String
d_writeXML : bool
get(const PropertyReceiver*) : String
set(PropertyReceiver*, const String&)
writeXMLToStream (const PropertyReceiver *,
XMLSerializer&)
CEGUI::PropertyReceiver
ConcreteProperty
ConcreteWidget
CEGUI::PropertyDefinitionBase
writeCausesRedraw : bool
writeCausesLayout : bool
p : ConcretePropery {static}
*
18
• concrete property...
• ... converts string from / to correct type
• ... casts receiver to correct target type
• ... goes trough public API
class Selected : public Property
{
public:
Selected() : Property("Selected", "Property to get/set the selected state
of the Checkbox. Value is either "True" or "False".", "False") {}
String get(const PropertyReceiver* receiver) const
{
return PropertyHelper::boolToString(
static_cast<const Checkbox*>(receiver)->isSelected());
}
void set(PropertyReceiver* receiver, const String& value)
{
static_cast<Checkbox*>(receiver)->setSelected(
PropertyHelper::stringToBool(value));
}
}
19
• PropertySet holds a list of properties
• every Widget is a PropertySet; adds its own properties to the list
ConcreteWidget
p : ConcretePropery {static}
CEGUI::PropertyReceiverCEGUI::PropertySet
void addProperty (Property *property)
getProperty (String &name) : String
setProperty (String &name, String &value)
CEGUI::Property
ConcreteProperty
*
*
20
String-Based Properties
• Problems:
• a lot of hand-written glue code
• inefficient string conversions for every access
• Pros:
• strings can be used for XML serialization
• property data held per class, not per instance
• goes through public interface of the class
• class can react to changes properly
21
Databases
• Idea:
• store all properties in a database (SQL / XML /
whatever)
• database API is single point of access for everything
• obvious for Browser / Online games
• Extreme: „There is no game entity class!“
• But:
• There is always some code representation of the data
• May not be feasable for small devices
• Speed / memory footprint?
22
Reflection (1)
• reflection
• ability of a program to observe its internal structure at
runtime
• assembly code in memory can be read and interpreted
• some scripting languages treat source code as strings
• typically on a high level
• figure out type of an object at runtime (introspection;
polymorphism)
• get the class name as a string
• get method names as strings
• figure out parameters and return types of methods
• supported by Objective C, Java, C#, VB .Net,
Managed C++
23
Reflection (2)
• how does it work?
• meta data generated by compiler
• special interfaces to query type info from objects (=
virtual functions)
• lots of string lookups at runtime
// trying to call: String FooNamespace.Foo.bar()
Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo");
MethodInfo methodInfo = obj.GetType().GetMethod("bar");
// invoke the method, supplying parameter array with 0 size
value = (String)methodInfo.Invoke(obj, new Object[0]);
C#
24
Reflection (3)
• Why doesn‘t C++ support this?
• no single-rooted hierarchy
• no common „Object“ base class for everything
• void* is most “compatible” type
• primitive types not really integrated into OO structure
• Java and .NET have wrapper classes for them
• .NET: “boxing” / “unboxing” mechanism
• C++ supports early and late binding
• i.e. supports non-virtual functions
• ... and classed without a VTable
• RTTI works for objects with VTable only
• VTable is not generated just for RTTI
25
Reflection (4)
• Reflection Libraries for C++ (just examples)
• Seal Reflex
• by European Organization for Nuclear Research (CERN)
• uses external tool (based on ) GCCXML) to parse C++ code and
generate reflection info
• non-intrusive; generates external dictionary for code
• up to date; supports latest gcc and VisualC++
• can add own meta-info to code (key-value-pairs)
• http://seal-reflex.web.cern.ch
Type t = Type::ByName("MyClass");
void * v = t.Allocate(); t.Destruct(v);
Object o = t.Construct();
for (Member_Iterator mi = t.Member_Begin(); mi != t.Member_End(); ++mi)
{
switch ((*mi).MemberType())
{
case DATAMEMBER : cout << "Datamember: " << (*mi).Name() << endl;
case FUNCTIONMEMBER : cout << "Functionmember: " << (*mi).Name() << endl;
}
}
26
Reflection (5)
• Reflection Libraries for C++ (just examples)
• CppReflection
• by Konstantin Knizhnik
• reflection info supplied partly by programmer (through macros)
• ... and partly taken from debug info generated by compiler
• http://www.garret.ru/~knizhnik/cppreflection/docs/reflect.html
class A
{
public:
int i;
protected:
long larr[10];
A** ppa;
public:
RTTI_DESCRIBE_STRUCT((RTTI_FIELD(i, RTTI_FLD_PUBLIC),
RTTI_ARRAY(larr, RTTI_FLD_PROTECTED),
RTTI_PTR_TO_PTR(ppa, RTTI_FLD_PROTECTED)));
};
27
Reflection (5)
• Boost Reflection
• by Jeremy Pack
• not part of the boost libraries yet!
• programmer must specify reflection info (through
macros / templates)
• http://boost-extension.blogspot.com
• also possible: COM and CORBA
• APIs that provide communication across language
boundaries
• also contain type description facilities
28
.NET Property System (1)
class CTestClass
{
private int iSomeValue;
public int SomeValue
{
get() { return iSomeValue; }
set() { iSomeValue = value; }
}
}
C#
CTestClass pTestClass = new CTestClass();
pTestClass.SomeValue = 42; // implicitly calls set()
System.Console.WriteLn(pTestClass.SomeValue); // implicitly calls get()
C#
• properties in .NET languages
• ... look like member variables to the outside
• ... but really are functions!
•  syntactic alternative to get/set functions
29
.NET Property System (2)
• just syntactic sugar?
ref class CTestClass
{
private:
int iSomeValue;
public:
property int SomeValue
{
int get() { return iSomeValue; }
void set(int value) { iSomeValue = value; }
}
}
Managed C++
CTestClass^ pTestClass = gcnew CTestClass;
pTestClass->SomeValue = 42;
System::Console::WriteLn(pTestClass->SomeValue);
Managed C++
30
.NET Property System (3)
• clean alternative to get/set methods
• look like one data field from the outside
• can still allow only get or only set
• can be abstract, inherited, overwritten, work with polymorphism
• interesting in connection with reflection
• reflection can tell difference between a „property“ and normal
methods
• can add custom attributes to properties
• through System.Attribute class
• e.g. description text, author name... anything you want
31
PropertyGrid control displays and
manipulates properties of any Object
using reflection.
32
property names
named property groups
description text for each property
custom editing controls
for different property types
validity criteria,
e.g. minimum/maximum value,
list of valid values
lists of predefined values
(but some of that
is domain knowledge the
editor has and not part
or the property system
33
• windows forms editor clearly using domain knowledge
to display special controls for some properties
• can figure out the names of the enum entries using refelection,
but not what „top“ or „fill“ means
public enum class DockStyle
{
Bottom,
Fill,
Left,
None,
Right,
Top
}
[LocalizableAttribute(true)]
public: virtual property DockStyle Dock
{
DockStyle get ();
void set (DockStyle value);
}
34
Homebrew Properties!
• accessing properties through functions  good idea!
• clean: uses public API
• object can react to changes
• hides implementation from outside
• Idea 1:
• use member function pointers
• i.e. existing get/set functions
• Idea 2:
• decouple per-instance and per-class data
• type information needs to be kept only once per class!
35
CGenericProperty
pUserObj : void*
pDescription: CGenericPropertyDescription*
GetTypeId() : type_info&;
GetName() : string;
GetDescriptionText() : string;
GetSemantic() : string;
GetDescription() : string;
GetReadOnly() : string;
CGenericPropertyDescription
LoadFromString(void* pObject, const string& rsString)
SaveToString(const void* pObject, string& rsString)
m_sName : std::string;
m_pType : const type_info*;
m_sDesciptionText : std::string;
m_bReadOnly : bool;
m_sSemantic : std::string;
per instance data:
- client object
- pointer to description
= 8 bytes
per class data
size does not really matter
property fetches most info
from here
36
• CProperty does not add any data members!
• can create array of CGenericProperty values and
cast them as needed
• not using polymorphism
CGenericProperty
pUserObj : void*
pDescription: CGenericPropertyDescription*
CProperty
SetValue(T)
GetValue() : T
T : typename
37
CGenericPropertyDescription
name, type, description, semantic...
CGenericProperty
GetValue(const void* pObject) : T
SetValue(void* pObject, T xValue)
CPropertyDescriptionScalar
void (USERCLASS::*m_fpSetFunction)(T);
T (USERCLASS::*m_fpGetFunction)() const;
T m_xDefaultValue;
T m_xMinValue;
T m_xMaxValue;
T : typename
USERCLASS: typename
T : typename
CPropertyDescriptionEnum
void (USERCLASS::*m_fpSetFunction)(int);
int (USERCLASS::*m_fpGetFunction)() const;
int m_iDefaultValue;
std::vector<string> m_asPossibleValues;
USERCLASS: typename
works for:
char, short, long, float, double
Vec2, Vec3
contains enum values as
strings
38
CPropertyDescriptionString<CCheckBox, string> CCheckBox::Prop_Text(
"Text", "Text that appears next to CheckBox", false, "",
&CCheckBox::SetText, &CCheckBox::GetText);
CPropertyDescriptionEnum<CCheckBox> CCheckBox::Prop_State(
"State", "Current state", false, "Unchecked", "Unchecked Checked Default",
&CCheckBox::SetChecked, &CCheckBox::GetChecked);
void
CCheckBox::GetProperties(vector<CGenericProperty>& apxProperties) const
{
__super::GetProperties(apxProperties);
apxProperties.push_back(CGenericProperty(&Prop_Text, (void*) this));
apxProperties.push_back(CGenericProperty(&Prop_State, (void*) this));
}
class CCheckBox
{
enum CheckBoxState { CB_Unchecked, CB_Checked, CB_Default };
void SetChecked(int p_eChecked = CB_Checked);
int GetChecked() const;
void SetText(string sText);
string GetText() const;
void GetProperties(vector<CGenericProperty>& apxProperties) const;
};
39
Homebrew Properties!
• semantic
• gives editor a hint how property is used
• a string property could be...
• ... a file name
• ... a font name
• ... or just a string
• Validation / Range data
• Different for each type
• Scalar : min / max / default value
• Enum: list of named values, default value
• String: max length, allowed characters, default value
40
if you want the slides:
david.salz@bitfield.de
Questions / Comments?
Thank you!

Weitere ähnliche Inhalte

Was ist angesagt?

Game object models - Game Engine Architecture
Game object models - Game Engine ArchitectureGame object models - Game Engine Architecture
Game object models - Game Engine ArchitectureShawn Presser
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Graham Wihlidal
 
Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4jrouwe
 
Horizon Zero Dawn: The Early Days
Horizon Zero Dawn: The Early DaysHorizon Zero Dawn: The Early Days
Horizon Zero Dawn: The Early DaysDevGAMM Conference
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by StepBayu Sembada
 
The Guerrilla Guide to Game Code
The Guerrilla Guide to Game CodeThe Guerrilla Guide to Game Code
The Guerrilla Guide to Game CodeGuerrilla
 
Pharo 11: A stabilization release
Pharo 11: A stabilization releasePharo 11: A stabilization release
Pharo 11: A stabilization releaseESUG
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and MoreMark Kilgard
 
온라인 게임 처음부터 끝까지 동적언어로 만들기
온라인 게임 처음부터 끝까지 동적언어로 만들기온라인 게임 처음부터 끝까지 동적언어로 만들기
온라인 게임 처음부터 끝까지 동적언어로 만들기Seungjae Lee
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기Sang Heon Lee
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기현철 조
 
Futex Scaling for Multi-core Systems
Futex Scaling for Multi-core SystemsFutex Scaling for Multi-core Systems
Futex Scaling for Multi-core SystemsDavidlohr Bueso
 
FrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in FrostbiteFrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in FrostbiteElectronic Arts / DICE
 
Multiplayer Game Sync Techniques through CAP theorem
Multiplayer Game Sync Techniques through CAP theoremMultiplayer Game Sync Techniques through CAP theorem
Multiplayer Game Sync Techniques through CAP theoremSeungmo Koo
 
Unity 3D
Unity 3DUnity 3D
Unity 3Dgema123
 
Intro to Massively Multiplayer Online Game (MMOG) Design
Intro to Massively Multiplayer Online Game (MMOG) DesignIntro to Massively Multiplayer Online Game (MMOG) Design
Intro to Massively Multiplayer Online Game (MMOG) DesignChristopher Mohritz
 

Was ist angesagt? (20)

Game object models - Game Engine Architecture
Game object models - Game Engine ArchitectureGame object models - Game Engine Architecture
Game object models - Game Engine Architecture
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016
 
Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4Killzone Shadow Fall: Threading the Entity Update on PS4
Killzone Shadow Fall: Threading the Entity Update on PS4
 
Beyond porting
Beyond portingBeyond porting
Beyond porting
 
God Of War : post mortem
God Of War : post mortemGod Of War : post mortem
God Of War : post mortem
 
Horizon Zero Dawn: The Early Days
Horizon Zero Dawn: The Early DaysHorizon Zero Dawn: The Early Days
Horizon Zero Dawn: The Early Days
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by Step
 
The Guerrilla Guide to Game Code
The Guerrilla Guide to Game CodeThe Guerrilla Guide to Game Code
The Guerrilla Guide to Game Code
 
Qemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System EmulationQemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System Emulation
 
Pharo 11: A stabilization release
Pharo 11: A stabilization releasePharo 11: A stabilization release
Pharo 11: A stabilization release
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and More
 
온라인 게임 처음부터 끝까지 동적언어로 만들기
온라인 게임 처음부터 끝까지 동적언어로 만들기온라인 게임 처음부터 끝까지 동적언어로 만들기
온라인 게임 처음부터 끝까지 동적언어로 만들기
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
 
Game design doc template
Game design doc   templateGame design doc   template
Game design doc template
 
Futex Scaling for Multi-core Systems
Futex Scaling for Multi-core SystemsFutex Scaling for Multi-core Systems
Futex Scaling for Multi-core Systems
 
FrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in FrostbiteFrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in Frostbite
 
Multiplayer Game Sync Techniques through CAP theorem
Multiplayer Game Sync Techniques through CAP theoremMultiplayer Game Sync Techniques through CAP theorem
Multiplayer Game Sync Techniques through CAP theorem
 
Unity 3D
Unity 3DUnity 3D
Unity 3D
 
Intro to Massively Multiplayer Online Game (MMOG) Design
Intro to Massively Multiplayer Online Game (MMOG) DesignIntro to Massively Multiplayer Online Game (MMOG) Design
Intro to Massively Multiplayer Online Game (MMOG) Design
 

Ähnlich wie A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)

Getting started with C++
Getting started with C++Getting started with C++
Getting started with C++Michael Redlich
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++Michael Redlich
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
COMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and SoliCOMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and SoliMark Billinghurst
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptvinu28455
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろうUnity Technologies Japan K.K.
 
Online java training ppt
Online java training pptOnline java training ppt
Online java training pptvibrantuser
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Dina Goldshtein
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 

Ähnlich wie A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig) (20)

Java
Java Java
Java
 
Getting started with C++
Getting started with C++Getting started with C++
Getting started with C++
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Java Advanced Features
Java Advanced FeaturesJava Advanced Features
Java Advanced Features
 
Dr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot netDr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot net
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
COMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and SoliCOMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and Soli
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.ppt
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Introduction_to_Java.ppt
Introduction_to_Java.pptIntroduction_to_Java.ppt
Introduction_to_Java.ppt
 
Online java training ppt
Online java training pptOnline java training ppt
Online java training ppt
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 

Kürzlich hochgeladen

Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 

Kürzlich hochgeladen (20)

Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 

A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)

  • 1. 1 A simple and powerful property system for C++ GCDC 2008 David Salz david.salz@bitfield.de
  • 2. 2 • Bitfield • small studio from Berlin, Germany • founded in 2006 • developer for PC, DS, Wii • focus on casual games for PC and DS • advertising games for trade shows & events
  • 3. 3 • Bitfield • licensed DS middleware developer • BitEngineDS, high level game engine • used in 10 games so far • adventure, jump‘n‘run, puzzle games, pet simulation • www.bitfield.de
  • 4. 4 • Games Academy • founded in 2000 • based in Berlin and Frankfurt/Main • ~170 students • Hire our students! • Constantly looking for teachers and lecturers!
  • 5. 5 What is a Property System? class CCar { Vec3 position; DWORD color float max_speed; int ai_type; ... * 3d model * shader parameters * sounds etc. ... }; location 127.3, 0, 14.0 max speed 120 km/h color AI Type Easy Team 2 ▼ ▼ ▲ ... 3d model mini.x ...
  • 6. 6 Uses of Property Systems (1) • a property system can be used for a lot of things! • serialization • store objects on disc (or stream over network) • e.g. saved games, level file format, scene graph file format • undo / redo • figure out which properties were changed, store old value • = selective serialization • client / server synchronization • send changed properties to client/server • = selective serialization
  • 7. 7 Uses of Property Systems (2) • a property system can be used for a lot of things! • animation • change property values over time • e.g. animated GUIs, in-game cut-scenes • integration of scripting languages • automatically create „glue code“ to access object properties from scripting languages
  • 8. 8 What do we want? (1) • easy-to-use system • lightweight • cause as little performance and memory overhead as possible • performance may not be an issue for editors... • ...but may for serialization, animation, scripting languages • type safe • i.e. all C++ type safety and type conversion mechanisms should stay intact • non-intrusive • i.e. it should not require modification of the class whose properties are to be exposed • it might by part of an external library; source code may not be available
  • 9. 9 What do we want? (2) • support polymorphic objects • i.e. work correctly with virtual functions • be aware of C++ protection mechanisms • i.e. not violate const, private or protected modifiers • support real-time manipulation of objects with no extra code • i.e. the object should not need extra code to deal with a changed property at runtime
  • 10. 10 Existing Solutions • ... using data pointers • ... using strings • … using databases • ... using reflection • properties in Microsoft .NET • ... using member function pointers
  • 11. 11 Data Pointers (1) • „A Property Class for Generic C++ Member Access“ • by Charles Cafrelli, published in Game Programming Gems 2 • Idea: • store a pointer to the data (inside to object) • plus type information • plus name
  • 12. 12 Data Pointers (2) class Property { protected: union Data { int* m_int; float* m_float; string* m_string; bool* m_bool; }; enum Type { INT, FLOAT, STRING, BOOL, EMPTY }; Data m_data; Type m_type; string m_name; Property(string const& name, int* value); Property(string const& name, float* value); Property(string const& name, string* value); Property(string const& name, bool* value); ~Property (); bool SetUnknownValue(string const& value); bool Set(int value); bool Set(float value); bool Set(string const& value); bool Set(bool value); void SetName(string const& name); string GetName() const; int Getlnt(); float GetFloatf); string GetString(); bool GetBool(); }
  • 13. 13 Data Pointers (3) class PropertySet { protected: HashTable<Property>m_properties; public: PropertySet(); virtual -PropertySet(); void Register(string const& name, int* value); void Register(string const& name, float* value); void Register(string const& name, string* value); void Register(string const& name, bool* value); // look up a property Property* Lookup(string const& name); // get a list of available properties bool SetValue(string const& name, string* value); bool Set(string const& name, string const& value); bool Set(string const& name, int value); bool Set(string const& name, float value); bool Set(string const& name, bool value); bool Set(string const& name, char* value); }; class GameObj : public PropertySet { int m_test; GameObj() { Register("test",&m_test); } }; Property* testprop = aGameObj->Lookup("test"); int test_value = testprop->GetInt();
  • 14. 14 Data Pointers (4) • Problems: • Is it a good idea to modify a (private?) variable directly? •  need to notify object after property change! • objects carry unnecessary and redundant data • every GameObj holds string names for all properties... • ... and pointers to it’s own members! • support for more types? • could be done using templates • or by storing data as string internally
  • 15. 15 String-Based Properties • Idea: • store all properties as strings • convert from / to string as needed • used by CEGui • Crazy Eddie's GUI System; open source GUI • used with OGRE / Irrlicht game engines • used in several commercial games
  • 16. 16
  • 17. 17 • PropertyReceiver is just an empty class, used for type safety • there is a derived class for every property of every class (181 !) CEGUI::Property d_name : String d_help : String d_default : String d_writeXML : bool get(const PropertyReceiver*) : String set(PropertyReceiver*, const String&) writeXMLToStream (const PropertyReceiver *, XMLSerializer&) CEGUI::PropertyReceiver ConcreteProperty ConcreteWidget CEGUI::PropertyDefinitionBase writeCausesRedraw : bool writeCausesLayout : bool p : ConcretePropery {static} *
  • 18. 18 • concrete property... • ... converts string from / to correct type • ... casts receiver to correct target type • ... goes trough public API class Selected : public Property { public: Selected() : Property("Selected", "Property to get/set the selected state of the Checkbox. Value is either "True" or "False".", "False") {} String get(const PropertyReceiver* receiver) const { return PropertyHelper::boolToString( static_cast<const Checkbox*>(receiver)->isSelected()); } void set(PropertyReceiver* receiver, const String& value) { static_cast<Checkbox*>(receiver)->setSelected( PropertyHelper::stringToBool(value)); } }
  • 19. 19 • PropertySet holds a list of properties • every Widget is a PropertySet; adds its own properties to the list ConcreteWidget p : ConcretePropery {static} CEGUI::PropertyReceiverCEGUI::PropertySet void addProperty (Property *property) getProperty (String &name) : String setProperty (String &name, String &value) CEGUI::Property ConcreteProperty * *
  • 20. 20 String-Based Properties • Problems: • a lot of hand-written glue code • inefficient string conversions for every access • Pros: • strings can be used for XML serialization • property data held per class, not per instance • goes through public interface of the class • class can react to changes properly
  • 21. 21 Databases • Idea: • store all properties in a database (SQL / XML / whatever) • database API is single point of access for everything • obvious for Browser / Online games • Extreme: „There is no game entity class!“ • But: • There is always some code representation of the data • May not be feasable for small devices • Speed / memory footprint?
  • 22. 22 Reflection (1) • reflection • ability of a program to observe its internal structure at runtime • assembly code in memory can be read and interpreted • some scripting languages treat source code as strings • typically on a high level • figure out type of an object at runtime (introspection; polymorphism) • get the class name as a string • get method names as strings • figure out parameters and return types of methods • supported by Objective C, Java, C#, VB .Net, Managed C++
  • 23. 23 Reflection (2) • how does it work? • meta data generated by compiler • special interfaces to query type info from objects (= virtual functions) • lots of string lookups at runtime // trying to call: String FooNamespace.Foo.bar() Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo"); MethodInfo methodInfo = obj.GetType().GetMethod("bar"); // invoke the method, supplying parameter array with 0 size value = (String)methodInfo.Invoke(obj, new Object[0]); C#
  • 24. 24 Reflection (3) • Why doesn‘t C++ support this? • no single-rooted hierarchy • no common „Object“ base class for everything • void* is most “compatible” type • primitive types not really integrated into OO structure • Java and .NET have wrapper classes for them • .NET: “boxing” / “unboxing” mechanism • C++ supports early and late binding • i.e. supports non-virtual functions • ... and classed without a VTable • RTTI works for objects with VTable only • VTable is not generated just for RTTI
  • 25. 25 Reflection (4) • Reflection Libraries for C++ (just examples) • Seal Reflex • by European Organization for Nuclear Research (CERN) • uses external tool (based on ) GCCXML) to parse C++ code and generate reflection info • non-intrusive; generates external dictionary for code • up to date; supports latest gcc and VisualC++ • can add own meta-info to code (key-value-pairs) • http://seal-reflex.web.cern.ch Type t = Type::ByName("MyClass"); void * v = t.Allocate(); t.Destruct(v); Object o = t.Construct(); for (Member_Iterator mi = t.Member_Begin(); mi != t.Member_End(); ++mi) { switch ((*mi).MemberType()) { case DATAMEMBER : cout << "Datamember: " << (*mi).Name() << endl; case FUNCTIONMEMBER : cout << "Functionmember: " << (*mi).Name() << endl; } }
  • 26. 26 Reflection (5) • Reflection Libraries for C++ (just examples) • CppReflection • by Konstantin Knizhnik • reflection info supplied partly by programmer (through macros) • ... and partly taken from debug info generated by compiler • http://www.garret.ru/~knizhnik/cppreflection/docs/reflect.html class A { public: int i; protected: long larr[10]; A** ppa; public: RTTI_DESCRIBE_STRUCT((RTTI_FIELD(i, RTTI_FLD_PUBLIC), RTTI_ARRAY(larr, RTTI_FLD_PROTECTED), RTTI_PTR_TO_PTR(ppa, RTTI_FLD_PROTECTED))); };
  • 27. 27 Reflection (5) • Boost Reflection • by Jeremy Pack • not part of the boost libraries yet! • programmer must specify reflection info (through macros / templates) • http://boost-extension.blogspot.com • also possible: COM and CORBA • APIs that provide communication across language boundaries • also contain type description facilities
  • 28. 28 .NET Property System (1) class CTestClass { private int iSomeValue; public int SomeValue { get() { return iSomeValue; } set() { iSomeValue = value; } } } C# CTestClass pTestClass = new CTestClass(); pTestClass.SomeValue = 42; // implicitly calls set() System.Console.WriteLn(pTestClass.SomeValue); // implicitly calls get() C# • properties in .NET languages • ... look like member variables to the outside • ... but really are functions! •  syntactic alternative to get/set functions
  • 29. 29 .NET Property System (2) • just syntactic sugar? ref class CTestClass { private: int iSomeValue; public: property int SomeValue { int get() { return iSomeValue; } void set(int value) { iSomeValue = value; } } } Managed C++ CTestClass^ pTestClass = gcnew CTestClass; pTestClass->SomeValue = 42; System::Console::WriteLn(pTestClass->SomeValue); Managed C++
  • 30. 30 .NET Property System (3) • clean alternative to get/set methods • look like one data field from the outside • can still allow only get or only set • can be abstract, inherited, overwritten, work with polymorphism • interesting in connection with reflection • reflection can tell difference between a „property“ and normal methods • can add custom attributes to properties • through System.Attribute class • e.g. description text, author name... anything you want
  • 31. 31 PropertyGrid control displays and manipulates properties of any Object using reflection.
  • 32. 32 property names named property groups description text for each property custom editing controls for different property types validity criteria, e.g. minimum/maximum value, list of valid values lists of predefined values (but some of that is domain knowledge the editor has and not part or the property system
  • 33. 33 • windows forms editor clearly using domain knowledge to display special controls for some properties • can figure out the names of the enum entries using refelection, but not what „top“ or „fill“ means public enum class DockStyle { Bottom, Fill, Left, None, Right, Top } [LocalizableAttribute(true)] public: virtual property DockStyle Dock { DockStyle get (); void set (DockStyle value); }
  • 34. 34 Homebrew Properties! • accessing properties through functions  good idea! • clean: uses public API • object can react to changes • hides implementation from outside • Idea 1: • use member function pointers • i.e. existing get/set functions • Idea 2: • decouple per-instance and per-class data • type information needs to be kept only once per class!
  • 35. 35 CGenericProperty pUserObj : void* pDescription: CGenericPropertyDescription* GetTypeId() : type_info&; GetName() : string; GetDescriptionText() : string; GetSemantic() : string; GetDescription() : string; GetReadOnly() : string; CGenericPropertyDescription LoadFromString(void* pObject, const string& rsString) SaveToString(const void* pObject, string& rsString) m_sName : std::string; m_pType : const type_info*; m_sDesciptionText : std::string; m_bReadOnly : bool; m_sSemantic : std::string; per instance data: - client object - pointer to description = 8 bytes per class data size does not really matter property fetches most info from here
  • 36. 36 • CProperty does not add any data members! • can create array of CGenericProperty values and cast them as needed • not using polymorphism CGenericProperty pUserObj : void* pDescription: CGenericPropertyDescription* CProperty SetValue(T) GetValue() : T T : typename
  • 37. 37 CGenericPropertyDescription name, type, description, semantic... CGenericProperty GetValue(const void* pObject) : T SetValue(void* pObject, T xValue) CPropertyDescriptionScalar void (USERCLASS::*m_fpSetFunction)(T); T (USERCLASS::*m_fpGetFunction)() const; T m_xDefaultValue; T m_xMinValue; T m_xMaxValue; T : typename USERCLASS: typename T : typename CPropertyDescriptionEnum void (USERCLASS::*m_fpSetFunction)(int); int (USERCLASS::*m_fpGetFunction)() const; int m_iDefaultValue; std::vector<string> m_asPossibleValues; USERCLASS: typename works for: char, short, long, float, double Vec2, Vec3 contains enum values as strings
  • 38. 38 CPropertyDescriptionString<CCheckBox, string> CCheckBox::Prop_Text( "Text", "Text that appears next to CheckBox", false, "", &CCheckBox::SetText, &CCheckBox::GetText); CPropertyDescriptionEnum<CCheckBox> CCheckBox::Prop_State( "State", "Current state", false, "Unchecked", "Unchecked Checked Default", &CCheckBox::SetChecked, &CCheckBox::GetChecked); void CCheckBox::GetProperties(vector<CGenericProperty>& apxProperties) const { __super::GetProperties(apxProperties); apxProperties.push_back(CGenericProperty(&Prop_Text, (void*) this)); apxProperties.push_back(CGenericProperty(&Prop_State, (void*) this)); } class CCheckBox { enum CheckBoxState { CB_Unchecked, CB_Checked, CB_Default }; void SetChecked(int p_eChecked = CB_Checked); int GetChecked() const; void SetText(string sText); string GetText() const; void GetProperties(vector<CGenericProperty>& apxProperties) const; };
  • 39. 39 Homebrew Properties! • semantic • gives editor a hint how property is used • a string property could be... • ... a file name • ... a font name • ... or just a string • Validation / Range data • Different for each type • Scalar : min / max / default value • Enum: list of named values, default value • String: max length, allowed characters, default value
  • 40. 40 if you want the slides: david.salz@bitfield.de Questions / Comments? Thank you!