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

David Salz
David SalzCTO @ albiononline.com at Sandbox Interactive GmbH
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!
1 of 40

Recommended

Game object models - Game Engine Architecture by
Game object models - Game Engine ArchitectureGame object models - Game Engine Architecture
Game object models - Game Engine ArchitectureShawn Presser
2.1K views82 slides
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin) by
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)
Albion Online - Software Architecture of an MMO (talk at Quo Vadis 2016, Berlin)David Salz
10.1K views45 slides
Server side game_development by
Server side game_developmentServer side game_development
Server side game_developmentYekmer Simsek
3.8K views23 slides
Deterministic Simulation - What modern online games can learn from the Game B... by
Deterministic Simulation - What modern online games can learn from the Game B...Deterministic Simulation - What modern online games can learn from the Game B...
Deterministic Simulation - What modern online games can learn from the Game B...David Salz
1.4K views30 slides
How hard can it be - Ui development at keen games by
How hard can it be - Ui development at keen gamesHow hard can it be - Ui development at keen games
How hard can it be - Ui development at keen gamesJulien Koenen
2.1K views48 slides
State-Based Scripting in Uncharted 2: Among Thieves by
State-Based Scripting in Uncharted 2: Among ThievesState-Based Scripting in Uncharted 2: Among Thieves
State-Based Scripting in Uncharted 2: Among ThievesNaughty Dog
24.7K views162 slides

More Related Content

What's hot

Unreal Engine 4 Introduction by
Unreal Engine 4 IntroductionUnreal Engine 4 Introduction
Unreal Engine 4 IntroductionSperasoft
7.9K views25 slides
Scene Graphs & Component Based Game Engines by
Scene Graphs & Component Based Game EnginesScene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game EnginesBryan Duggan
7.1K views38 slides
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro... by
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...Gerke Max Preussner
1.5K views19 slides
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅 by
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅DongMin Choi
12.7K views123 slides
SPU Optimizations-part 1 by
SPU Optimizations-part 1SPU Optimizations-part 1
SPU Optimizations-part 1Naughty Dog
2.4K views62 slides
[NDC 2016] 유니티, iOS에서 LINQ 사용하기 by
[NDC 2016] 유니티, iOS에서 LINQ 사용하기[NDC 2016] 유니티, iOS에서 LINQ 사용하기
[NDC 2016] 유니티, iOS에서 LINQ 사용하기Daehee Kim
9.5K views46 slides

What's hot(20)

Unreal Engine 4 Introduction by Sperasoft
Unreal Engine 4 IntroductionUnreal Engine 4 Introduction
Unreal Engine 4 Introduction
Sperasoft7.9K views
Scene Graphs & Component Based Game Engines by Bryan Duggan
Scene Graphs & Component Based Game EnginesScene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game Engines
Bryan Duggan7.1K views
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro... by Gerke Max Preussner
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
Gerke Max Preussner1.5K views
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅 by DongMin Choi
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
DongMin Choi12.7K views
SPU Optimizations-part 1 by Naughty Dog
SPU Optimizations-part 1SPU Optimizations-part 1
SPU Optimizations-part 1
Naughty Dog2.4K views
[NDC 2016] 유니티, iOS에서 LINQ 사용하기 by Daehee Kim
[NDC 2016] 유니티, iOS에서 LINQ 사용하기[NDC 2016] 유니티, iOS에서 LINQ 사용하기
[NDC 2016] 유니티, iOS에서 LINQ 사용하기
Daehee Kim9.5K views
Artwork Personalization at Netflix Fernando Amat RecSys2018 by Fernando Amat
Artwork Personalization at Netflix Fernando Amat RecSys2018 Artwork Personalization at Netflix Fernando Amat RecSys2018
Artwork Personalization at Netflix Fernando Amat RecSys2018
Fernando Amat3.5K views
GRU4Rec v2 - Recurrent Neural Networks with Top-k Gains for Session-based Rec... by Balázs Hidasi
GRU4Rec v2 - Recurrent Neural Networks with Top-k Gains for Session-based Rec...GRU4Rec v2 - Recurrent Neural Networks with Top-k Gains for Session-based Rec...
GRU4Rec v2 - Recurrent Neural Networks with Top-k Gains for Session-based Rec...
Balázs Hidasi3.2K views
ECS (Part 1/3) - Introduction to Data-Oriented Design by Phuong Hoang Vu
ECS (Part 1/3) - Introduction to Data-Oriented DesignECS (Part 1/3) - Introduction to Data-Oriented Design
ECS (Part 1/3) - Introduction to Data-Oriented Design
Phuong Hoang Vu553 views
Ndc2012 최지호 텍스쳐 압축 기법 소개 by Jiho Choi
Ndc2012 최지호 텍스쳐 압축 기법 소개Ndc2012 최지호 텍스쳐 압축 기법 소개
Ndc2012 최지호 텍스쳐 압축 기법 소개
Jiho Choi6K views
Uncharted Animation Workflow by Naughty Dog
Uncharted Animation WorkflowUncharted Animation Workflow
Uncharted Animation Workflow
Naughty Dog12.3K views
Unreal Open Day 2017 UE4 for Mobile: The Future of High Quality Mobile Games by Epic Games China
Unreal Open Day 2017 UE4 for Mobile: The Future of High Quality Mobile GamesUnreal Open Day 2017 UE4 for Mobile: The Future of High Quality Mobile Games
Unreal Open Day 2017 UE4 for Mobile: The Future of High Quality Mobile Games
Epic Games China8.7K views
재미이론의 시사점과 게임 플레이 개선에 적용방안 by Sunnyrider
재미이론의 시사점과 게임 플레이 개선에 적용방안재미이론의 시사점과 게임 플레이 개선에 적용방안
재미이론의 시사점과 게임 플레이 개선에 적용방안
Sunnyrider 1.3K views
Building a turn-based game prototype using ECS - Unite Copenhagen 2019 by Unity Technologies
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Unity Technologies3.3K views
Game Engine Architecture by Attila Jenei
Game Engine ArchitectureGame Engine Architecture
Game Engine Architecture
Attila Jenei14.7K views
Optimization in Unity: simple tips for developing with "no surprises" / Anton... by DevGAMM Conference
Optimization in Unity: simple tips for developing with "no surprises" / Anton...Optimization in Unity: simple tips for developing with "no surprises" / Anton...
Optimization in Unity: simple tips for developing with "no surprises" / Anton...
DevGAMM Conference606 views
Approximate nearest neighbor methods and vector models – NYC ML meetup by Erik Bernhardsson
Approximate nearest neighbor methods and vector models – NYC ML meetupApproximate nearest neighbor methods and vector models – NYC ML meetup
Approximate nearest neighbor methods and vector models – NYC ML meetup
Erik Bernhardsson22.2K views
Killzone Shadow Fall: Creating Art Tools For A New Generation Of Games by Guerrilla
Killzone Shadow Fall: Creating Art Tools For A New Generation Of GamesKillzone Shadow Fall: Creating Art Tools For A New Generation Of Games
Killzone Shadow Fall: Creating Art Tools For A New Generation Of Games
Guerrilla12.5K views
온라인 게임 처음부터 끝까지 동적언어로 만들기 by Seungjae Lee
온라인 게임 처음부터 끝까지 동적언어로 만들기온라인 게임 처음부터 끝까지 동적언어로 만들기
온라인 게임 처음부터 끝까지 동적언어로 만들기
Seungjae Lee7.7K views
Kgc2012 온라인 게임을 위한 게임 오브젝트 설계 by kgun86
Kgc2012 온라인 게임을 위한 게임 오브젝트 설계Kgc2012 온라인 게임을 위한 게임 오브젝트 설계
Kgc2012 온라인 게임을 위한 게임 오브젝트 설계
kgun8610.5K views

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

Java by
Java Java
Java Prabhat gangwar
536 views50 slides
Getting started with C++ by
Getting started with C++Getting started with C++
Getting started with C++Michael Redlich
78 views39 slides
Getting Started with C++ by
Getting Started with C++Getting Started with C++
Getting Started with C++Michael Redlich
249 views39 slides
Introduction to java by
Introduction to javaIntroduction to java
Introduction to javaAbhishekMondal42
78 views15 slides
JavaScript in 2016 by
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
636 views65 slides
JavaScript in 2016 (Codemotion Rome) by
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
1.2K views65 slides

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

JavaScript in 2016 by Codemotion
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
Codemotion636 views
JavaScript in 2016 (Codemotion Rome) by Eduard Tomàs
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
Eduard Tomàs1.2K views
Core java complete ppt(note) by arvind pandey
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey5.9K views
COMP 4026 Lecture 5 OpenFrameworks and Soli by Mark Billinghurst
COMP 4026 Lecture 5 OpenFrameworks and SoliCOMP 4026 Lecture 5 OpenFrameworks and Soli
COMP 4026 Lecture 5 OpenFrameworks and Soli
Mark Billinghurst911 views
FI MUNI 2012 - iOS Basics by Petr Dvorak
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
Petr Dvorak960 views
UsingCPP_for_Artist.ppt by vinu28455
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.ppt
vinu284551 view
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう by Unity Technologies Japan K.K.
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
Online java training ppt by vibrantuser
Online java training pptOnline java training ppt
Online java training ppt
vibrantuser80 views
Look Mommy, No GC! (TechDays NL 2017) by Dina Goldshtein
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
Dina Goldshtein444 views
MFF UK - Introduction to iOS by Petr Dvorak
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
Petr Dvorak807 views
C# 7 development by Fisnik Doko
C# 7 developmentC# 7 development
C# 7 development
Fisnik Doko871 views

Recently uploaded

360 graden fabriek by
360 graden fabriek360 graden fabriek
360 graden fabriekinfo33492
165 views25 slides
ADDO_2022_CICID_Tom_Halpin.pdf by
ADDO_2022_CICID_Tom_Halpin.pdfADDO_2022_CICID_Tom_Halpin.pdf
ADDO_2022_CICID_Tom_Halpin.pdfTomHalpin9
5 views33 slides
JioEngage_Presentation.pptx by
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptxadmin125455
8 views4 slides
Airline Booking Software by
Airline Booking SoftwareAirline Booking Software
Airline Booking SoftwareSharmiMehta
9 views26 slides
Top-5-production-devconMunich-2023-v2.pptx by
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptxTier1 app
8 views42 slides
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...Stefan Wolpers
42 views38 slides

Recently uploaded(20)

360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492165 views
ADDO_2022_CICID_Tom_Halpin.pdf by TomHalpin9
ADDO_2022_CICID_Tom_Halpin.pdfADDO_2022_CICID_Tom_Halpin.pdf
ADDO_2022_CICID_Tom_Halpin.pdf
TomHalpin95 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254558 views
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta9 views
Top-5-production-devconMunich-2023-v2.pptx by Tier1 app
Top-5-production-devconMunich-2023-v2.pptxTop-5-production-devconMunich-2023-v2.pptx
Top-5-production-devconMunich-2023-v2.pptx
Tier1 app8 views
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by Stefan Wolpers
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
Stefan Wolpers42 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
Understanding HTML terminology by artembondar5
Understanding HTML terminologyUnderstanding HTML terminology
Understanding HTML terminology
artembondar57 views
Electronic AWB - Electronic Air Waybill by Freightoscope
Electronic AWB - Electronic Air Waybill Electronic AWB - Electronic Air Waybill
Electronic AWB - Electronic Air Waybill
Freightoscope 5 views
Bootstrapping vs Venture Capital.pptx by Zeljko Svedic
Bootstrapping vs Venture Capital.pptxBootstrapping vs Venture Capital.pptx
Bootstrapping vs Venture Capital.pptx
Zeljko Svedic15 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views
How to build dyanmic dashboards and ensure they always work by Wiiisdom
How to build dyanmic dashboards and ensure they always workHow to build dyanmic dashboards and ensure they always work
How to build dyanmic dashboards and ensure they always work
Wiiisdom14 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8714 views

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!