Cocos2d3.2 event mechanism source code analysis
Cocos2d events are divided into TOUCH, KEYBOARD, ACCELERATION, MOUSE, FOCUS, GAME_CONTROLLER, and CUSTOM, which are TOUCH, KEYBOARD, ACCELERATION, MOUSE, FOCUS, game controller, and CUSTOM events. With the event, you need an event listener. Each event corresponds to at least one listener. Because the touch is divided into single-point touch and multi-point touch, the touch event corresponds to two kinds of listeners, each listener defines a listenerid.
The following two steps are used to analyze the source code:
1 ---- register the listener
Cocos2d provides two methods to register listeners: addEventListenerWithFixedPriority and addEventListenerWithSceneGraphPriority.
void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority)void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node)
The former parameter has a priority, and the latter binds the listener to a node. Therefore, the listener callback trigger will receive the influence of globalZorder and localZorder of node. The default priority of addEventListenerWithSceneGraphPriority is 0. The smaller the priority, the sooner the listener is triggered. When the event is swallowed up, the listener will not be triggered. There are two ways to swallow the listener:
Event-> stopPropagation (); listener-> setSwallowTouches (true); // limited to single-point touch
Void EventDispatcher: addEventListener (EventListener * listener) {if (_ inDispatch = 0) // the event is not currently being distributed. force it to the listener list {forceAddEventListener (listener );} else {_ toAddedListeners. push_back (listener); // Add to the pending addition list} listener-> retain ();}When the dispatch event ends, the wait list is added to the listener list.
Void EventDispatcher: updateListeners (Event * event) {CCASSERT (_ inDispatch> 0, If program goes here, there shocould be event in dispatch .); //.... omitting some code ......... if (! _ ToAddedListeners. empty () {for (auto & listener: _ toAddedListeners) {forceAddEventListener (listener);} _ toAddedListeners. clear ();}}
_ ListenerMap maintains a ing from listenerId to EventListenerVector. In EventListenerVector, _ fixedListeners and _ sceneGraphListeners are added to push a listener, it determines the list to which it is placed based on its priority. When a new listener is added, a dirty data is written, which identifies the _ fixedListeners and _ sceneGraphListeners in the listenerId listener, before distributing an event, you must determine whether the current event will be affected by the dirty data. If there is an impact, you need to re-sort the list before dispatching.
Void EventDispatcher: forceAddEventListener (EventListener * listener) {EventListenerVector * listeners = nullptr; EventListener: ListenerID listenerID = listener-> getListenerID (); auto itr = _ listenerMap. find (listenerID); if (itr = _ listenerMap. end () {listeners = new (std: nothrow) EventListenerVector (); _ listenerMap. insert (std: make_pair (listenerID, listeners);} else {listeners = itr-> second;} // EventListenerVector includes _ fixedListeners and _ optional listeners-> push_back (listener); if (listener-> getFixedPriority () = 0) {setDirty (listenerID, DirtyFlag :: SCENE_GRAPH_PRIORITY); auto node = listener-> getAssociatedNode (); CCASSERT (node! = Nullptr, Invalid scene graph priority !); Listener (node, listener); if (node-> isRunning () {resumeEventListenersForTarget (node) ;}} else {setDirty (listenerID, DirtyFlag: FIXED_PRIORITY );}}
// ID of the listenerID list to be changed. Whether it is _ fixedListeners or _ sceneGraphListeners depends on flagvoid EventDispatcher: setDirty (const EventListener: ListenerID & listenerID, DirtyFlag flag) {auto iter = _ priorityDirtyFlagMap. find (listenerID); if (iter = _ priorityDirtyFlagMap. end () {_ priorityDirtyFlagMap. insert (std: make_pair (listenerID, flag);} else {int ret = (int) flag | (int) iter-> second; iter-> second = (DirtyFlag) ret ;}}
2 ----- event dispatch
// Dispatch events, first process dirty data, sort listeners, and dispatch
Void EventDispatcher: dispatchEvent (Event * event) {if (! _ IsEnabled) return; // dirty data not only exists when the listener is added, but also dirty data is generated when the node resume bound to the listener already exists, only the listener updateDirtyFlagForSceneGraph () in _ sceneGraphListeners is affected; // identifies the event being distributed DispatchGuard (_ inDispatch); if (Event-> getType () = event: Type :: TOUCH) {// handle dispatchTouchEvent (static_cast
(Event); return;} auto listenerID = _ getListenerID (event); // sort listenerID listeners (if needed) // DirtyFlag :: FIXED_PRIORITY --------> fixedPriorityListeners sorting // DirtyFlag: SCENE_GRAPH_PRIORITY --------> sceneGraphPriorityListeners sorting sortEventListeners (listenerID); auto iter = _ listenerMap. find (listenerID); if (iter! = _ ListenerMap. end () {auto listeners = iter-> second; auto onEvent = [& event] (EventListener * listener) -> bool {event-> setCurrentTarget (listener-> getAssociatedNode (); listener-> _ onEvent (event); return event-> isStopped (); // whether the event is swallowed up}; // dispatch the event in sequence dispatchEventToListeners (listeners, onEvent);} updateListeners (event );}
Trigger a touch event. A single touch event triggers an event at each touch point. A multi-touch event is processed by group.
Void EventDispatcher: dispatchTouchEvent (EventTouch * event) {// sortEventListeners (listener: LISTENER_ID); auto parts = getListeners (listener :: LISTENER_ID); auto allAtOnceListeners = getListeners (EventListenerTouchAllAtOnce: LISTENER_ID); // If there aren't any touch listeners, directreturn ly. if (nullptr = oneByOneListeners & nullptr = allAtOnceListeners) return; bool isNeedsMutableSet = (oneByOneListeners & allAtOnceListeners); const std: vector
& Amp; originalTouches = event-> getTouches (); std: vector
MutableTouches (originalTouches. size (); // save a set of touch points std: copy (originalTouches. begin (), originalTouches. end (), mutableTouches. begin (); // process the target handlers 1st // if (oneByOneListeners) {auto mutableTouchesIter = mutableTouches. begin (); auto touchesIter = originalTouches. begin (); for (; touchesIter! = OriginalTouches. end (); ++ touchesIter) {bool isSwallowed = false; // process each touch point. auto onTouchEvent = [&] (EventListener * l) -> bool {// Return true to break EventListenerTouchOneByOne * listener = static_cast
(L); // Skip if the listener was removed. if (! Listener-> _ isRegistered) return false; event-> setCurrentTarget (listener-> _ node); bool isClaimed = false; // whether std: vector is claimed
: Iterator removedIter; EventTouch: EventCode eventCode = event-> getEventCode (); if (eventCode = EventTouch: EventCode: BEGAN) {if (listener-> onTouchBegan) {isClaimed = listener-> onTouchBegan (* touchesIter, event); if (isClaimed & listener-> _ isRegistered) {// Add the touch point to the listener claim list, when processing the MOVED, ENDED, and CANCELLED events, the corresponding touch point must be in the claim list. Otherwise, the corresponding method listener-> _ claimedTouches is not triggered. push_back (* touchesIter) ;}}// can you find BEGA? N added touch points. else if (listener-> _ claimedTouches. size ()> 0 & (removedIter = std: find (listener-> _ claimedTouches. begin (), listener-> _ claimedTouches. end (), * touchesIter ))! = Listener-> _ claimedTouches. end () {isClaimed = true; switch (eventCode ){//........ omitting some code ......... if (listener-> _ isRegistered ){
// When the touch ends, the touch point must be removed from the claim list. Otherwise, the list is very large, and CANCELLED is the same.
Listener-> _ claimedTouches. erase (removedIter );
}//........ Omitting some code .........}} // If the event was stopped, return directly. // swallowed events: method 1 if (event-> isStopped () {updateListeners (event); return true; // block listener processing} CCASSERT (* touchesIter) -> getID () = (* mutableTouchesIter)-> getID (),); // swallowed events: method 2 if (isClaimed & listener-> _ isRegistered & listener-> _ needSwallow) {if (isNeedsMutableSet) {// because the touch event of this point is swallowed up, the next multi-point touch will not trigger this touch point. mutableTouchesIter = m UtableTouches. erase (mutableTouchesIter); isSwallowed = true;} return true; // block listener processing} return false;}; // dispatchEventToListeners (oneByOneListeners, onTouchEvent ); if (event-> isStopped () // This type of devouring event is more powerful. After a stop event is triggered, it not only affects the listener after a single touch, but also blocks the processing of multi-touch events {return ;} if (! IsSwallowed) ++ mutableTouchesIter;} // the next step is multi-point touch // process standard handlers 2nd // if (allAtOnceListeners & mutableTouches. size ()> 0) // If a touch point event is not swallowed up {//......... if you omit some code, the callback is triggered ..............} updateListeners (event );}
Events are triggered for each listener in the sorted listener list. events with priority less than 0, sceneGraphPriorityListeners, and those with priority greater than 0 are triggered first.
Void EventDispatcher: dispatchEventToListeners (EventListenerVector * listeners, const std: function
& OnEvent) {bool shouldStopPropagation = false; auto fixedPriorityListeners = listeners-> getFixedPriorityListeners (); auto outcome = listeners-> consume (); ssize_t I = 0; // priority <0 if (fixedPriorityListeners) {CCASSERT (listeners-> getGt0Index () <= static_cast
(FixedPriorityListeners-> size (), Out of range exception !); If (! FixedPriorityListeners-> empty ()){//.......... omitting part of the code ................}} if (sceneGraphPriorityListeners) {if (! ShouldStopPropagation) {// priority = 0, scene graph priority for (auto & l: * sceneGraphPriorityListeners ){//.......... omitting some code ................}}} if (fixedPriorityListeners) {if (! ShouldStopPropagation) {// priority> 0 ssize_t size = fixedPriorityListeners-> size (); for (; I <size; ++ I) {//.......... omitting some code ................}}}}
We often talk about listener sorting. Next, let's look at how to sort in order. The sorting of fixedListeners is quite simple. The whole list is done with a sorting function, but sceneGraphListeners is quite troublesome, first, it needs to calculate the depth of all subnodes. The depth depends on globalZorder and localZorder. when accessing a node, it needs to perform access in the descending order of localZorder, add the current node when localZorder = 0, and then access the subnode of localZorder> 0.
Void EventDispatcher: sortEventListenersOfSceneGraphPriority (const EventListener: ListenerID & listenerID, Node * rootNode ){//.......... omit part of the code ................ // Reset priority index _ nodePriorityIndex = 0; _ nodePriorityMap. clear (); // Save the depth of all nodes // access all nodes and calculate the depth of each node. This step is critical to visitTarget (rootNode, true); // After sort: priority <0,> 0 std: sort (sceneGraphListeners-> begin (), sceneGraphListeners-> end (), [this] (const EventListener * l1, const EventListener * l2) {return _ nodePriorityMap [l1-> getAssociatedNode ()]> _ nodePriorityMap [l2-> getAssociatedNode ()] ;}); // ...... omit part of the code ................}
Specific computing depth:
Void EventDispatcher: visitTarget (Node * node, bool isRootNode) {int I = 0; auto & children = node-> getChildren (); auto childrenCount = children. size (); if (childrenCount> 0) {// Access Node * child = nullptr in the order described above; // visit children zOrder <0 (; I <childrenCount; I ++) {child = children. at (I); if (child & child-> getLocalZOrder () <0) visitTarget (child, false); else break;} if (_ nodeListen ErsMap. find (node )! = _ NodeListenersMap. end () {// After accessing the subnode of localZorder <0, add the subnode to the corresponding globalZorder list. Note that the order of adding the globalZorder list is also very orderly. _ GlobalZOrderNodeMap [node-> getGlobalZOrder ()]. push_back (node) ;}for (; I <childrenCount; I ++) {child = children. at (I); if (child) visitTarget (child, false) ;}} else {if (_ nodeListenersMap. find (node )! = _ NodeListenersMap. end () {// leaf node, add the node to the corresponding globalZorder list to _ globalZOrderNodeMap [node-> getGlobalZOrder ()]. push_back (node) ;}} if (isRootNode) {std: vector
GlobalZOrders; globalZOrders. reserve (_ globalZOrderNodeMap. size (); for (const auto & e: _ globalZOrderNodeMap) {globalZOrders. push_back (e. first);} std: sort (globalZOrders. begin (), globalZOrders. end (), [] (const float a, const float B) {return a <B ;}); for (const auto & globalZ: globalZOrders) {for (const auto & n: _ globalZOrderNodeMap [globalZ]) {_ nodePriorityMap [n] = ++ _ nodePriorityIndex; // computing depth} _ globalZOrderNodeMap. clear ();}}