I am writing a simple application to learn some basic Dart programming but I can't work out the structure and inclusions - I get a Duplicate class Point
First of all, I have my main class I called MouseTrack. It initializes the list and will have a loop.
#import('dart:html');
#import('Eye.dart');
class MouseTrace {
List<Eye> eyes;
...
}
Secondly, I have a class called Eye, which is supposed to hold information of of an eye as a circle. It's quite simple:
#library('app:eye');
#import('dart:html'); // without this one, I get no error but I want to have it to use CanvasRenderingContext2D
#import('Point.dart');
class Eye {
Point position;
num radius;
Eye() :
position = new Point() {
}
void draw(CanvasRenderingContext2D context) {
// draws a circle
}
}
And finally Point:
#library('app:point');
class Point {
num x, y;
Point(this.x, this.y);
}
What I want to achieve is 3 separate classes - main, Eye and Point, so I can have instances of Eye in main (for simplicity & nice model) and instances of Point in Eye (for storing position). At least that's how I'm used to doing.
P.S I know I can skip types but I want it there and I guess it's a problem with inclusions rather than the language (and want to fix it so I know how to do it properly).
P.S.S. I have cut off some code so that you don't have to read everything but, if you want, I will post it all.
Problem lies in the app:eye library (in the Eye.dart file). You import dart:html and app:point libraries, but both of them define a Point class. This situation is invalid. You can solve it either by not importing dart:html at all, if you don't need it, or prefixing one of those imports:
#import('dart:html', prefix: 'html');
#import('Point.dart');
In this case, you will have to refer to names from dart:html by using a html. prefix. In your case, if you want to use the CanvasRenderingContext2D class, you will have to write html.CanvasRenderingContext2D instead.
Related
Edit: So far it looks like the answer to my question is, "You can't do that in Swift." I currently have a solution whereby the subclass names are listed in an array and I loop around and instantiate them to trigger the process I'm describing below. If this is the best that can be done, I'll switch it to a plist so that least it's externally defined. Another option would be to scan a directory and load all files found, then I would just need to make sure the compiler output for certain classes is put into that directory...
I'm looking for a way to do something that I've done in C++ a few times. Essentially, I want to build a series of concrete classes that implement a particular protocol, and I want to those classes to automatically register themselves such that I can obtain a list of all such classes. It's a classic Prototype pattern (see GoF book) with a twist.
Here's my approach in C++; perhaps you can give me some ideas for how to do this in Swift 4? (This code is grossly simplified, but it should demonstrate the technique.)
class Base {
private:
static set<Base*> allClasses;
Base(Base &); // never defined
protected:
Base() {
allClasses.put(this);
}
public:
static set<Base*> getAllClasses();
virtual Base* clone() = 0;
};
As you can see, every time a subclass is instantiated, a pointer to the object will be added to the static Base::allClasses by the base class constructor.
This means every class inherited from Base can follow a simple pattern and it will be registered in Base::allClasses. My application can then retrieve the list of registered objects and manipulate them as required (clone new ones, call getter/setter methods, etc).
class Derived: public Base {
private:
static Derived global; // force default constructor call
Derived() {
// initialize the properties...
}
Derived(Derived &d) {
// whatever is needed for cloning...
}
public:
virtual Derived* clone() {
return new Derived(this);
}
};
My main application can retrieve the list of objects and use it to create new objects of classes that it knows nothing about. The base class could have a getName() method that the application uses to populate a menu; now the menu automatically updates when new subclasses are created with no code changes anywhere else in the application. This is a very powerful pattern in terms of producing extensible, loosely coupled code...
I want to do something similar in Swift. However, it looks like Swift is similar to Java, in that it has some kind of runtime loader and the subclasses in this scheme (such as Derived) are not loaded because they're never referenced. And if they're not loaded, then the global variable never triggers the constructor call and the object isn't registered with the base class. Breakpoints in the subclass constructor shows that it's not being invoked.
Is there a way to do the above? My goal is to be able to add a new subclass and have the application automatically pick up the fact that the class exists without me having to edit a plist file or doing anything other than writing the code and building the app.
Thanks for reading this far — I'm sure this is a bit of a tricky question to comprehend (I've had difficulty in the past explaining it!).
I'm answering my own question; maybe it'll help someone else.
My goal is to auto initialize subclasses such that they can register with a central authority and allow the application to retrieve a list of all such classes. As I put in my edited question, above, there doesn't appear to be a way to do this in Swift. I have confirmed this now.
I've tried a bunch of different techniques and nothing seems to work. My goal was to be able to add a .swift file with a class in it and rebuild, and have everything automagically know about the new class. I will be doing this a little differently, though.
I now plan to put all subclasses that need to be initialized this way into a particular directory in my application bundle, then my AppDelegate (or similar class) will be responsible for invoking a method that scans the directory using the filenames as the class names, and instantiating each one, thus building the list of "registered" subclasses.
When I have this working, I'll come back and post the code here (or in a GitHub project and link to it).
Same boat. So far the solution I've found is to list classes manually, but not as an array of strings (which is error-prone). An a array of classes such as this does the job:
class AClass {
class var subclasses: [AClass.Type] {
return [BClass.self, CClass.self, DClass.self]
}
}
As a bonus, this approach allows me to handle trees of classes, simply by overriding subclasses in each subclass.
I would like to have a semantic named custom element that extends from button: like fab-button
class FabButton extends HTMLButtonElement {
constructor() {
super();
this.html = hyperHTML.bind(this);
}
}
customElements.define("fab-button", FabButton);
Extending for HTMLButtonElement doesn't seem to work.
Is there a way to extend from a non-HTMLElement with the HyperHTML "document-register-element.js"?
Codepen example:
https://codepen.io/jovdb/pen/qoRare
It's difficult to answer this, because it's tough to understand where to start from.
The TL;DR solution though, is here, but it needs a lot of explanations.
Extending built-ins is a ghost in the Web specs
It doesn't matter what WHATWG says, built-ins are a de-facto death specification because Webkit strongly opposed to it and Firefox, as well as Edge, that never even shipped Custom Elements, didn't push to have them neither.
Accordingly, as starting point, it's discouraged to extend built-ins with Custom Elements V1 specification.
You might have luck with V0 though, but that's only Chrome API and it's already one of those APIs created to die (R.I.P. WebSQL).
My polyfill follows specs by definition
The document-register-element polyfill, born with V0 but revamped with V1, follows specifications as close as possible, which is why it makes extending built-ins possible, because WHATWG still has that part in.
That also means you need to understand how extending built-ins works.
It is not by defining a simple class that extends HTMLButtonElement that you get a button, you need to do at least three extra things:
// define via the whole signature
customElements.define(
"fab-button",
FabButton,
{extends: 'button'}
);
... but also ... allow the polyfill to work
// constructor might receive an instance
// and such instance is the upgraded one
constructor(...args) {
const self = super(...args);
self.html = hyperHTML.bind(self);
return self;
}
and most important, its most basic representation on the page would be like this
<button is="fab-button">+</button>
Bear in mind, with ES6 classes super(...args) would always return the current context. It's there to grant super constructors didn't return other instances as upgraded objects.
The constructor is not your friend
As harsh as it sounds, Custom Elements constructors work only with Shadow DOM and addEventListener, but nothing else, really.
When an element is created is not necessarily upgraded yet. in fact, it won't be, most likely, upgraded.
There are at least 2 bugs filed to every browser and 3 inconsistent behaviors about Custom Elements initialization, but your best bet is that once connectedCallback is invoked, you really have the custom element node content.
connectedCallback() {
this.slots = [...this.childNodes];
this.render();
}
In that way you are sure you actually render the component once live on the DOM, and not when there is not even a content.
I hope I've answered your question in a way that also warns you to go away from custom elements built-ins if that's the beginning of a new project: they are unfortunately not a safe bet for the future of your application.
Best Regards.
Edit: This question is not off-topic as it describes an issue in data file handling with Turbo C++.
First of all, Turbo C++ is because of my school. Don't comment telling me to stop using it, I'm forced.
Introduction: I'm trying to build a DFH library, so I made all these functions to write, read, insert, delete, modify, etc.
I used stings to make the functions work for any filename passed to them.
What I understand (self-learned) from the whole making a class and then passing it's object in the read_stream.read((char*)& Object_1, sizeof(Object_1)); form to read the file, that you wrote using the same object is that: the class works as sort of a template to print data onto the file.
Question: I want to use them with different objects of different classes, so the class whose object these DFH functions use for performing the desired task should be sort of like a template.
I was thinking on doing something with templates or abstract class and inheritance but I'm a beginner so I need someone to point me in the right direction!
To clear up: I want to use the same functions by just including this source file into other programs containing different classes.
Example Code
class Data {
int user_id;
public:
void enter() { //Input Function
cout<<"\nID: ";
cin>>user_id;
};
void write(char* file_1) { //File Write Function
clrscr();
Data Object_1;
char ch;
int records_read =0;
ofstream fout;
fout.open(file_1, ios::binary|ios::noreplace);
do {
records_read++;
Object_1.enter(records_read);
fout.write((char*)& Object_1, sizeof(Object_1));
cout<<"\nDo you want to continue? Y/N - ";
cin>>ch;
} while((ch=='y')||(ch=='Y'));
cout<<"\nWrite Successful!";
fout.close();
}
How do I make the function write() work with any other class, without having to explicitly change the statement Data Object_1; ?
Good day! I just started studying Unreal Engine 4.12 for a week now. For your discretion - I have little knowledge in C++ programming. (Although I code using PHP so I understanding OOP to some extent) - and, I'm just getting a little familiar with visual scripting (blueprint).
What I want to do is change the players weapon by loading a new static mesh, that static mesh would be from a file path. There are currently no blueprint node that does that, many articles/forums are suggesting to build my own blueprint node.
I've done some research and I have found this: Dynamic Load Object C++ - and it is very promising - but, I have no knowledge of implementing it. I tried opening MyProject.h and pasted it there, I'm not sure what to do next - does it become a function? Or a blueprint node?
I 'am open to other suggestions (or directions) on how to achieve what I wanted. If there are other methods to achieve this, please share and educate me. Thank you very much!
Sincerely,
Chris
That static load is only helper. You can call C++ function only if you mark header of that function by UFUNCTION(...) macro. See this link.
So you can create your function and in it's implementation, you can call that helper. For example:
// Helpers.h
static FORCEINLINE UTexture2D* GetTexture2DByName(const FName& name) {
return LoadObjFromPath<UTexture2D>(name);
}
UFUNCTION(BlueprintCallable, Category = TCF2Helpers)
static UTexture2D* GetTexture2DForBlock(UBuildableBlockInfo* blockInfo);
// Helpers.cpp
UTexture2D* UHelpers::GetTexture2DForBlock(UBuildableBlockInfo* blockInfo)
{
if (!blockInfo)
return nullptr;
const FString baseFolder = TEXT("Texture2D'/Game/Textures/HUD/%s");
if (blockInfo->IsEmptyHand)
return GetTexture2DByName(*FString::Printf(*baseFolder, TEXT("EmptyHand.EmptyHand'")));
// another lines of implementation
}
But you need to ask yourself, if you really need to have it hardcoded. You can specify something like
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
TSubclassOf<class UObjectWidget> wInGameMenu;
UPROPERTY(BlueprintReadOnly, Category = "Widgets")
UObjectWidget* InGameMenu;
where in override of function BeginPlay (this is due to creating widget on the fly) I have:
if (wInGameMenu)
{
InGameMenu = CreateWidget<UObjectWidget>(this, wInGameMenu);
}
UObjectWidget is successor of UUserWidget and my widgets (created in Editor) are reparented to have that widget as an inheretance base. I define which widget should be created on archetype of my object which holds it.
I'd implement it like that: (this may be changed if anyone tells me better way)
Create WeaponManager as ActorComponent
Create Weapon as SceneComponent (so you can attach it on skeleton socket)
Every Weapon will have it's own implementation based on same interface (maybe override of some functions defined in common ancestor?)
You can have multiple sub-childs (Energy weapon, shooting weapon etc) so you have correct inheritance and you avoid multiple implementation of same thing.
Every Weapon will define it's mesh and properties - again, if you hardcoded mesh path (it's OK since it is implementation), you can use code like that in the end of that list) or you can set that on archetype, if you'd like to code something in blueprint.
Then in WeaponManager you define all weapons (for example TArray<TSubclassOf<UWeapon>>
Every Weapon should define EWeaponType - enum af all weapons in game, so I can match defined weapons with it's type in TMap and then simply work with it on demand (show, hide, change weapon etc.) That type should be hardcoded to all implementations of weapons.
Load mesh in constructor:
//TerminalObject.h
UCLASS()
class TAUCETIF2_API ATerminalObject : public AStaticMeshActor
{
GENERATED_UCLASS_BODY()
};
// TerminalObject.cpp
ATerminalObject::ATerminalObject(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
static ConstructorHelpers::FObjectFinder<UStaticMesh> mesh(TEXT("StaticMesh'/Game/BuildingObjects/Meshes/terminal.terminal'"));
checkf(mesh.Succeeded(), TEXT("Failed to find mesh"));
auto mc = GetStaticMeshComponent();
checkf(mc, TEXT("Failed to find mesh component"));
mc->SetStaticMesh(mesh.Object);
}
Good day! I am new to using Unreal Engine 4 and I have a few questions about how exactly blueprints work. From my understanding of it, every blueprint works like a class. By that I mean one blueprint is much like one class in an OOP programming language.
Please educate me as to - if my assumption is correct or wrong. If wrong, then maybe you could help me achieve what I want in a different method/perspective. I am willing to learn and accept suggestions.
If at some point my understanding is correct - that blueprints are actually individual classes - I would really appreciate it if you could (please) guide as to where to go and how to implement a design that I want to create. This is from a programmers perspective (PHP OOP Programming). Forgive the approach, I'm just using PHP to logically express how I want the class to work. Plus, it is the only OOP programming I know atm.
I want to create a class named: Items. class Item {}
This class is going to handle everything item related, thus we will have to give it a lot of properties/variable. (Below is just an example; Again I'm using PHP as an example.)
class Item {
var $id;
var $name;
var $description;
var $type;
var $subType;
var $mesh;
var $materials;
}
3.) I would like to initiate this class by having two variables as its construct arguments. (We will require itemID and itemType). This is because I will use these two variables to retrieve the item's data which is already available in a data table. I will use those data in the table to populate the class properties/variables. (I'm not sure if I said that right. I hope you understood my point anyway.)
class Item {
var $id;
var $name;
var $description;
var $type;
var $subType;
var $mesh;
var $materials;
function _construct($cons_itemID, $cons_itemType) {
/*-- Start getting the item Data here based on what item and type provided. Then, push that data into the class properties/variables. We will use individual methods/functions to fill other properties/variables later. --*/
}
}
4.) Basically with that design I could easily pass on an item ID to the class and then get the item's name, description, mesh, materials and etc using pointers.
Example:
$weapon = new Item('10001','Weapon');
$weaponMesh = $weapon->getMesh();
$armor = new Item('12345','Armor');
$armorName = $armor->getName();
I'm just having a lot of trouble working with blueprint and achieve this method or even something similar to it. I'm not trying to avoid C++, I would love to learn it but I just don't have the time freedom right now.
Few things I have tried to make it work:
Casting / Casting to class (But I couldn't figure out what the target object will be and how was I going to add input arguments into the class that way? There isn't any input there that I could use.)
Spawn Actor (This one is very promising, I need to dig in deeper into this)
Blueprint Macros? Blueprint Interfaces? (I'm just lost.)
For all those who will help or answer. Thank you!
~ Chris
So far as I know, yes, we can assume that each blueprint can be viewed as class. (Moreover, since UE 4.12 (in UE 4.11 that functionality is marked as experimental I think) you can check Compile blueprints under Project settings -> Packaging. That will create native class for each blueprint.)
You can create either Blueprint or C++ class based on Object (UObject in C++). Then you can specify all properties (or variables in UE editor terminology). In BP you have small advantage: you can mark some properties as Visible at spawn (they must be Public and Visible). So when you are creating new instance of that class, you can explicitly pass values to that properties.
And in BP Construct event, that properties are correctly filled, thus you can set another properties values based on given ID and Type.
In C++ class having different arguments than FObjectInitializer is not possible, thus you don't have that values in time when constructor is executed. But it is not so hard to achieve same functionality, you can find example here: https://answers.unrealengine.com/questions/156055/passing-arguments-to-constructors-in-ue4.html.
Something about list of what you had tried:
Spawn actor - derive from actor only if you intend to have that BP in scene. Actors are subjects to game updates and rendering, so having actor only as data container is very wrong.
BP Macro is same as BP Function except function will be called just like function (so executing necesary actions by function call conventions) and macro will replace it's implementation in place, where you are calling that macro. More exhausting explanation here.
If I would implement your code, I'd do it like I said and then I'll have that class as property in some component and that component would be attached to some actor, which would be placed in scene.