Integrating smart pointers with legacy code raw pointers - pointers

I have a situation, where I have existing code that works with raw pointers, and I'm not permitted to smart-pointer-ify it. However, I am permitted to use smart pointers in any new code I develop.
For example.
I have an existing function like:
void processContent()
{
ContentObject * myContent = new ContentObject();
newFunction(myContent);
}
void newFunction(ContentObject * content)
{
// myVector is just a std::vector<ContentObject*>, defined elsewhere
myVector.push_back(content);
}
void doSomethingWithContent()
{
// There is some logic here, but ultimately based on this logic I want to remove entries, and free the memory they point to.
myVector.pop_back();
}
I have control over the content of "newFunction" and "doSomethingWithContent". But the argument passed into newFunction is fixed. Obviously I could manually delete the pointer in myVetor, before popping it, but I wondered if I can implement smart pointers here so that it happens "automatically" for me?
Can I take a raw pointer passed into a function, and turn it into a unique_ptr, then add this to a container, and have it delete the memory when it's popped from the container?
Thanks
Joey

Assume that you can define your myVector as the following:
std::vector<std::shared_ptr<ContentObject>> myVector;
In that case you can switch on smart pointers in your code and myVector will keep all your objects as you expected:
void newFunction(ContentObject * content)
{
myVector.push_back(std::shared_ptr<ContentObject>(content));
}
void doSomethingWithContent()
{
// There is some logic here, but ultimately based on this logic I want to remove entries, and free the memory they point to.
myVector.pop_back();
}

Related

How to turn off Motion Controller line pointer

That's it, I'll step on my pride!
I'm using MRTK v2 and working fine except that at some point I want to turn off the line extending from the Motion Controller to the object and that provides input. After looking around and trying to find it in the MRTK documentation (it's gotta be easy, right?), I'm still banging my head on the wall and it's starting to hurt....
The MRTK documentation explains quite well how to configure it here:
https://github.com/microsoft/MixedRealityToolkit-Unity/blob/mrtk_release/Documentation/Input/Pointers.md
But I'm looking to do this in script, enabling and disabling it as I need it in my application.
Any clue how to do this?
Many thanks!
Answered my own question. Simple:
PointerUtils.SetMotionControllerRayPointerBehavior(PointerBehavior.AlwaysOff);
See documentation here: https://github.com/microsoft/MixedRealityToolkit-Unity/blob/mrtk_release/Documentation/Input/Pointers.md
Great question! Here's one way to do this that has worked for me. You can see my solution at this repository: https://github.com/julenka/MixedRealityToolkit-Unity/tree/so/linepointer_off. Open the scene Assets/TurnOffLinePointerTest.unity and then use hand simulation to press the buttons. The code to turn the pointers on/off is in Assets/PointerConfigurationExample.cs.
Note: the reason you need to use this approach of modifying the mediator instead of directly setting myPointer.IsActive = false is because the default mediator overwrites these values every frame. Luckily, you can customize this behavior.
Step 1: Update MRTK a bit so that PointerMediator can be accessed
Apply the changes from this commit to your MRTK clone. This change updates the FocusProvider in MRTK to make the PointerMediator publicly accessible, and makes the DefaultPointerMediator extensible by updating fields to be protected instead of private, and making methods virtual. See this pull request that implements this change directly into MRTK.
Step 2: Create a custom PointerMediator that will turn off far pointers
Create a custom Pointer Mediator like the one from this commit.
using System.Collections.Generic;
using Microsoft.MixedReality.Toolkit.Input;
public class CustomPointerMediator : DefaultPointerMediator
{
public bool FarPointersDisabled {get; set;}
public override void UpdatePointers()
{
base.UpdatePointers();
if (FarPointersDisabled)
{
foreach(var pointer in farInteractPointers)
{
pointer.IsActive = false;
}
}
}
}
Note that this mediator extends DefaultPointerMediator so it adapts almost all the default mediator logic. Make sure you have fully applied the changes from the first commit otherwise you will not be able to extend DefaultPointerMediator.
Step 3: Tell MRTK to use your custom pointer mediator
In your pointer profile, configure MRTK to use the custom pointer mediator instead of the default pointer mediator. Notice in the picture that I've created a custom pointer profile as part of a custom input system (don't modify the default profile otherwise your changes might get overwritten when you update MRTK).
Step 4: Component that uses custom mediator to turn line pointers on / off
You can now write your component which will use your custom mediator to turn the line pointers on and off.
public class PointerConfigurationExample : MonoBehaviour
{
/* Turns off all far interaction pointers */
public void TurnOffFarPointers()
{
Debug.Log("Line pointers off");
SetFarPointersDisabled(true);
}
public void TurnOnFarPointers()
{
Debug.Log("Line pointers on");
SetFarPointersDisabled(false);
}
private void SetFarPointersDisabled(bool isDisabled)
{
FocusProvider focusProvider = (FocusProvider) MixedRealityToolkit.InputSystem.FocusProvider;
if (focusProvider != null)
{
foreach(var mediator in focusProvider.PointerMediators)
{
// Note: you could check here to make sure you only disable pointers for hands
CustomPointerMediator myMediator = (CustomPointerMediator) (mediator.Value);
if (myMediator != null)
{
myMediator.FarPointersDisabled = isDisabled;
}
}
}
}
}

DayDream, detect pointer without using Event System

Google's new DayDream samples are using the Event System to detect if the pointer is on an object.
Previously it wasn't working like that at all, it was a reticle, and you would then create a Raycast between the Camera and the reticle, such as:
Vector3 rayDirection = GvrController.Orientation * Vector3.forward;
if (Physics.Raycast(origin, rayDirection, out hitInfo, Mathf.Infinity)) {
And then you detect if a specific Object is between the reticle and the Camera.
This way doesn't exactly work anymore. Google is now using the event system, and then checking if the reticle is positioned on an object.
Is there a way for me to check that for any object without using the Event System.
The Event System is a good method, it's just I have about 40 different objects that all work the same way, and implementing an event point/click for these 40 different objects seems like an overkill when previously I could just check an object by tag.
Anyone was able by any chance to be able to detect if the pointer is positioned on an object without using the Event system?
Raycasts don't seem to properly work anymore as the pointer seems to be more of a 2D object, just like a Mouse.
This works approximately, but not very well:
Vector3 origin = Head.transform.position + GvrController.ArmModel.wristPosition;
Vector3 rayDirection = GvrController.ArmModel.pointerRotation * Vector3.forward;
Any help would be appreciated :)
If you don't want to use EventTrigger component, you can simply use your same old script and implement IPointerEnterHandler, IPointerExitHandler, OnPointerClickHandler etc and use same compare tag method for every object.
I think its much more easy to use than custom raycast. As there is always a Graphics Raycaster (or Physics Raycaster for 3D Objects) at work so why not use what it has to offer.
public class MyOldScriptWhichUsedRaycasting: MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
public void OnPointerEnter (PointerEventData eventData)
{
if(gameObject.CompareTag("Grabable"))
{
//do stuff here.
}
}
public void OnPointerExit (PointerEventData eventData)
{
if(gameObject.CompareTag("Grabable"))
{
//do stuff here.
}
}
public void OnPointerClick (PointerEventData eventData)
{
if(gameObject.CompareTag("Grabable"))
{
//do stuff here.
}
}
}
Hope this helps

Recursively turning a stack into a linked list

so I have been working on a programming assignment that involves taking a stack implementation of size ~13,000 and turning it into a linked list. The guide is basically that the stack was filled by sequentially scanning a linked list (IE tail would be the top of the stack), and you want to re create the linked list using the stack. The trick is you have to do it using a recursive method. The only methods in this stack class are pop (returns and removes the top element), and isEmpty(tells if the stack is empty). I have code that gets the job done, however it requires increasing the java stack size (otherwise I get StackOverflowError), which I feel like that isn't allowed.
That being said does anyone know a way I could possibly get this to work without increasing the java stack size.
The stack is a static field I have labeled S. Head is what should be the first node in the linked list, and steper is simply a node to be used to create every other step.
Here is the code I currently have:
public static void stackToList()
{
int x = 0;
if(S.isEmpty())
{
return;
}
x = S.pop();
stackToList();
if (head == null)
{
head = new ListNode(x, null);
steper = head;
}
else
{
steper.next = new ListNode(x, null);
steper = steper.next;
}
}
Thank you ahead of time for any help.
It is happening because you are keeping an entire list of function calls in memory stack. You start creating your linked list only after you reach to the bottom of the stack thus keeping all the previous calls to stackList waiting to be over.
You need to start creating your linked list with the first pop of stack.
A simple & non tested (not worked in Java in a very long time now) function may look like:
public static ListNode stackToList(ListNode head) {
if(S.isEmpty())
return head;
int stackValue = S.pop();
ListNode node = ListNode(stackValue, null);
node.next(head);
return stackToList(node);
}
And you call it like:
ListNode head = stackToList(null)
HTH
EDIT: Now that I posted it, I realized that my code has potentially the same issue as yours, because I remembered Java doesn't support tail-call optimization.
It's not entirely clear from your question if you're using java.util.LinkedList and java.util.Stack but since you didn't provide the code for these objects I will be using those in my example solution below:
public static void main(String[] args) {
//Create a stack
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
//Create a list to hold your stack elements
LinkedList<Integer> linkedList = new LinkedList<Integer>();
//Call the conversion method, which modifies both the stack and the list
convertStackToLinkedList(stack, linkedList);
//print the results
System.out.println("linkedList: "+linkedList);
}
public static void convertStackToLinkedList(Stack<Integer> stack, LinkedList<Integer> linkedList){
int topStackElement = stack.pop();
linkedList.add(0,topStackElement);
if(!stack.isEmpty())
convertStackToLinkedList(stack, linkedList);
}
I suspect you may not be using java.util.LinkedList since your code is attempting to modify the internals of the list. So, you would simply need to implement a method similar to that of the add(int index, E element) method in the java.util.LinkedList class and then use it in your recursion. I assume you can do this if you have access to the internals of the list.
EDIT:
I forgot to mention that I agree with the answer by Harsh Gupta in that the reason you're seeing StackOverflowError is that you're waiting until you reach the end of your recursion to modify your list. In some recursion you have to wait until the end but if you don't have to wait don't do it.

C++ CLI : A way to prevent function from returning to its caller?

Perhaps there is a fancy term for this. Lets say I have this code:
void a(){
b();
}
void b(){
c();
}
void c(){
a();
// do something
if (FLAG_COMPLETE){
return;
}
}
The problem is it will go a->b->c->a->b->c until it FLAG_COMPLETE goes up. After it will track back through ALL those calls in back order. Is there a way to avoid the return to caller function from the callee? I know in assembly this would be quite easy to do.
I am using C++ CLI. I want to avoid overflowing the stack by calling functions in a loop.
If I read between the lines, it sounds like you want the contents of a(), then b(), then c(), to run forever, until FLAG_COMPLETE is set? If that's the case, then why not do that explicitly?
void RunUntilComplete()
{
while(!FLAG_COMPLETE)
{
ContentsOfA();
ContentsOfB();
ContentsOfC();
}
}

Making a reference-counted object in D using RefCounted!(T)

How do you use std.typecons.RefCounted!(T) to make a reference-counted object in D?
I've tried to figure out what std.array.Array does internally by looking at the source, but while I can read the source, I just can't figure what a "payload" is or how it all works when there's things like bitwise struct copying involved, as well as why some things are duplicated in the internal and external structure.
Could anyone provide an example or a link on how to use it to, say, wrap a simple Win32 HANDLE?
Thanks!
Disclaimer: I haven't tested my claims, just read the documentation.
Payload is referring to what is being stored. In your case the payload is the Win32 HANDLE. Since HANDLE is just an integer you wouldn't want to do:
auto refHandle = RefCounted!HANDLE(WhatGetsMeAHandle());
Because a Windows function will need to be called when the handle goes out of scope.
In std.containers.Array what you saw was a struct called Payload, which had a field called _payload. The structure is going to be the storage of the data, accessed through _payload. This provides a level of indirection to be utilized later.
You will notice that RefCounted is actually used on the Array structure. This means the destructor for that struct will only be called when the reference count is 0. So the ~this() inside of Payload is where you would want to clean up the your HANDLE.
What is happening: since struct is a value type, every time the structure goes out of scope the destructor is called, there isn't one for Array, but Payload is wrapped in a RefCounted, the destructor for RefCounted!Payload is also called. And only when the reference count reaches zero is the destructor for Payload itself called.
Now, RefCounted itself has reference semantics, this means that having an Array a, you can then assign to auto b = a; and everything will be copied over, but RefCounted has a postblits defined meaning the data will not be copied, but the reference count will be
incremented.
I will now try and provide you with a wrapper outline for what you want. It will probably help you visualize the information above, but it may not be entirely correct. Let me know if something needs fixing.
struct MyWinWrapper {
struct Payload {
HANDLE _payload;
this(HANDLE h) { _payload = h; }
~this() { freeHandleHere(_payload); }
// Should never perform these operations
this(this) { assert(false); }
void opAssign(MyWinWrapper.Payload rhs) { assert(false); }
}
private alias RefCounted!(Payload, RefCountedAutoInitialize.no) Data;
private Data _data;
this(HANDLE h) { _data = Data(h); }
}
Since there is no default constructor for a struct you will probably want to provide a free function that returns this structure.

Resources