public GlobalContactManager(Context context) { this.context = context; File file = context.getDatabasePath("none"); File databaseDir = file.getParentFile(); File[] listFiles = databaseDir.listFiles(); List<String> yjtUserIds = getYjtUserIds(context); for (int i = 0; i < listFiles.length; i++) { File dbFile = listFiles[i]; String name = dbFile.getName(); if (name.matches(CONTACT_DB_REGULAR)) { ContactManager contactManager = ContactManager.createContactManagerWithDBHelper( context, new ContactDBHelper(context, name)); String userId = name.substring(4); if (yjtUserIds.contains(userId)) { yjtUserContactManagers.add(contactManager); } else if (AccountManager.getCurrent(context).getId() != Long.parseLong(userId)) { contactManagers.add(contactManager); } else { // current user contactManager currentContactManager = ContactManager.getContactManager(context); } } } if (currentContactManager == null) { currentContactManager = ContactManager.getContactManager(context); } }
/** * Take a time step. This performs collision detection, integration, and constraint solution. * * @param timeStep the amount of time to simulate, this should not vary. * @param velocityIterations for the velocity constraint solver. * @param positionIterations for the position constraint solver. */ public void step(float dt, int velocityIterations, int positionIterations) { stepTimer.reset(); // log.debug("Starting step"); // If new fixtures were added, we need to find the new contacts. if ((m_flags & NEW_FIXTURE) == NEW_FIXTURE) { // log.debug("There's a new fixture, lets look for new contacts"); m_contactManager.findNewContacts(); m_flags &= ~NEW_FIXTURE; } m_flags |= LOCKED; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0.0f) { step.inv_dt = 1.0f / dt; } else { step.inv_dt = 0.0f; } step.dtRatio = m_inv_dt0 * dt; step.warmStarting = m_warmStarting; // Update contacts. This is where some contacts are destroyed. tempTimer.reset(); m_contactManager.collide(); m_profile.collide = tempTimer.getMilliseconds(); // Integrate velocities, solve velocity constraints, and integrate positions. if (m_stepComplete && step.dt > 0.0f) { tempTimer.reset(); solve(step); m_profile.solve = tempTimer.getMilliseconds(); } // Handle TOI events. if (m_continuousPhysics && step.dt > 0.0f) { tempTimer.reset(); solveTOI(step); m_profile.solveTOI = tempTimer.getMilliseconds(); } if (step.dt > 0.0f) { m_inv_dt0 = step.inv_dt; } if ((m_flags & CLEAR_FORCES) == CLEAR_FORCES) { clearForces(); } m_flags &= ~LOCKED; // log.debug("ending step"); m_profile.step = stepTimer.getMilliseconds(); }
private GlobalContact queryContactWithPhoneInContactManagers( String phone, List<ContactManager> contactManagers) { if (!contactManagers.isEmpty()) { for (ContactManager contactManager : contactManagers) { GlobalContact globalContact = contactManager.getContactByPhone(phone); if (globalContact != null) { return globalContact; } } } return null; }
/** * Overrides the Behaviour.action() method. This method is executed by the agent thread. It * basically defines two sub behaviours, which are in charge of periodically updating the DF and * receiving DF notifications. */ public void action() { try { // first thing to do is to register on the df and save current location if any DFAgentDescription myDescription = new DFAgentDescription(); // fill a msn service description ServiceDescription msnServiceDescription = new ServiceDescription(); msnServiceDescription.setName(MsnAgent.msnDescName); msnServiceDescription.setType(MsnAgent.msnDescType); myDescription.addServices(msnServiceDescription); ContactManager.getInstance().resetModifications(); DFAgentDescription[] onlineContacts = DFService.search(myAgent, myDescription); updateContactList(onlineContacts); MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT); Map<String, Contact> cMap = ContactManager.getInstance().getAllContacts(); Map<String, ContactLocation> cLocMap = ContactManager.getInstance().getAllContactLocations(); ContactListChanges changes = ContactManager.getInstance().getModifications(); myLogger.log( Logger.FINE, "Thread " + Thread.currentThread().getId() + "After reading local contacts and first df query: " + "Adding to VIEW_REFRESH_EVENT this list of changes: " + changes.toString()); event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LISTOFCHANGES, changes); event.addParam(MsnEvent.VIEW_REFRESH_CONTACTSMAP, cMap); event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LOCATIONMAP, cLocMap); MsnEventMgr.getInstance().fireEvent(event); DFUpdaterBehaviour updater = new DFUpdaterBehaviour(myAgent, msnUpdateTime, myContactLocation); MsnAgent agent = (MsnAgent) myAgent; DFSubscriptionBehaviour subBh = new DFSubscriptionBehaviour(myAgent, agent.getSubscriptionMessage()); myAgent.addBehaviour(updater); myAgent.addBehaviour(subBh); } catch (Exception e) { // TODO Auto-generated catch block myLogger.log(Logger.SEVERE, "Severe error: ", e); e.printStackTrace(); } }
/** * Overrides the TickerBehaviour, defining how to update the location on the df (registration to * DF has already been performed during agent setup). Three properties are defined for storing * latitude/longitude/altitude. Only latitude and longitude are used, though. */ protected void onTick() { try { MsnAgent agent = (MsnAgent) myAgent; DFAgentDescription description = agent.getAgentDescription(); ServiceDescription serviceDescription = (ServiceDescription) description.getAllServices().next(); serviceDescription.clearAllProperties(); // retrieve ContactLocation curMyLoc = ContactManager.getInstance().getMyContactLocation(); if (!curMyLoc.equals(myContactLocation)) { Property p = new Property(PROPERTY_NAME_LOCATION_LAT, new Double(curMyLoc.getLatitude())); serviceDescription.addProperties(p); p = new Property(PROPERTY_NAME_LOCATION_LONG, new Double(curMyLoc.getLongitude())); serviceDescription.addProperties(p); p = new Property(PROPERTY_NAME_LOCATION_ALT, new Double(curMyLoc.getAltitude())); serviceDescription.addProperties(p); DFService.modify(myAgent, description); myContactLocation = curMyLoc; } } catch (FIPAException fe) { myLogger.log(Logger.SEVERE, "Error in updating DF", fe); } catch (Exception e) { myLogger.log( Logger.SEVERE, "*** Uncaught Exception for agent " + myAgent.getLocalName() + " ***", e); } }
public void release() { List<ContactManager> contactManagers = this.contactManagers; for (ContactManager contactManager : contactManagers) { contactManager.release(); } contactManagers.clear(); this.contactManagers = null; List<ContactManager> yjtUserContactManagers = this.yjtUserContactManagers; for (ContactManager contactManager : yjtUserContactManagers) { contactManager.release(); } yjtUserContactManagers.clear(); this.yjtUserContactManagers = null; this.currentContactManager = null; this.context = null; }
protected Object formBackingObject(HttpServletRequest request) throws Exception { int contactId = RequestUtils.getRequiredIntParameter(request, "contactId"); Contact contact = contactManager.getById(new Long(contactId)); AddPermission addPermission = new AddPermission(); addPermission.setContact(contact); return addPermission; }
public GlobalContact queryContactWithPhone(String phone) { GlobalContact globalContact = queryContactWithPhoneInYJTUserContactManager(phone); if (globalContact != null) { return globalContact; } globalContact = currentContactManager.getContactByPhone(phone); if (globalContact != null) { return globalContact; } globalContact = queryContactWithPhoneInOtherContactManager(phone); return globalContact; }
private Map listRecipients(HttpServletRequest request) { Map map = new LinkedHashMap(); map.put( "", getApplicationContext() .getMessage("select.pleaseSelect", null, "-- please select --", request.getLocale())); Iterator recipientsIter = contactManager.getAllRecipients().iterator(); while (recipientsIter.hasNext()) { String recipient = (String) recipientsIter.next(); map.put(recipient, recipient); } return map; }
/** * Utility method that updates the contact list extracting contact info and location from DF * descriptions. * * @param onlineContactsDescs array of {@link DFAgentDescription} objects that define services as * results of a DF query */ private void updateContactList(DFAgentDescription[] onlineContactsDescs) { for (int i = 0; i < onlineContactsDescs.length; i++) { Iterator serviceDescIt = onlineContactsDescs[i].getAllServices(); if (serviceDescIt.hasNext()) { ServiceDescription desc = (ServiceDescription) serviceDescIt.next(); Iterator propertyIt = desc.getAllProperties(); Location loc = Helper.extractLocation(propertyIt); AID cId = onlineContactsDescs[i].getName(); if (!cId.equals(myAgent.getAID())) { // Create an online contact (or update it) String phoneNumber = cId.getLocalName(); ContactManager.getInstance().addOrUpdateOnlineContact(phoneNumber, loc); } } } }
protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { AddPermission addPermission = (AddPermission) command; PrincipalSid sid = new PrincipalSid(addPermission.getRecipient()); Permission permission = BasePermission.buildFromMask(addPermission.getPermission().intValue()); try { contactManager.addPermission(addPermission.getContact(), sid, permission); } catch (DataAccessException existingPermission) { existingPermission.printStackTrace(); errors.rejectValue("recipient", "err.recipientExistsForContact", "Addition failure."); return showForm(request, response, errors); } return new ModelAndView(new RedirectView(getSuccessView())); }
/** * Initializes the <code>KoLmafia</code> session. Called after the login has been confirmed to * notify that the login was successful, the user-specific settings should be loaded, and the user * can begin adventuring. */ public static void initialize(final String username) { // Load the JSON string first, so we can use it, if necessary. ActionBarManager.loadJSONString(); // Initialize the variables to their initial states to avoid // null pointers getting thrown all over the place // Do this first to reset per-player item aliases ItemDatabase.reset(); KoLCharacter.reset(username); // Get rid of cached password hashes in KoLAdventures AdventureDatabase.refreshAdventureList(); // Reset all per-player information ChatManager.reset(); MailManager.clearMailboxes(); StoreManager.clearCache(); DisplayCaseManager.clearCache(); ClanManager.clearCache(); CampgroundRequest.reset(); MushroomManager.reset(); HermitRequest.initialize(); SpecialOutfit.forgetCheckpoints(); KoLmafia.updateDisplay("Initializing session for " + username + "..."); Preferences.setString("lastUsername", username); // Perform requests to read current character's data StaticEntity.getClient().refreshSession(); // Reset the session tally and encounter list StaticEntity.getClient().resetSession(); // Open the session log and indicate that we've logged in. RequestLogger.openSessionLog(); if (Preferences.getBoolean("logStatusOnLogin")) { KoLmafiaCLI.DEFAULT_SHELL.executeCommand("log", "snapshot"); } // If the password hash is non-null, then that means you // might be mid-transition. if (GenericRequest.passwordHash.equals("")) { PasswordHashRequest request = new PasswordHashRequest("lchat.php"); RequestThread.postRequest(request); } ContactManager.registerPlayerId(username, String.valueOf(KoLCharacter.getUserId())); if (Preferences.getString("spadingData").length() > 10) { KoLmafia.updateDisplay( "Some data has been collected that may be of interest " + "to others. Please type `spade' to examine and submit or delete this data."); } // Rebuild Scripts menu if needed GenericFrame.compileScripts(); if (StaticEntity.getClient() instanceof KoLmafiaGUI) { KoLmafiaGUI.intializeMainInterfaces(); } else if (Preferences.getString("initialFrames").indexOf("LocalRelayServer") != -1) { KoLmafiaGUI.constructFrame("LocalRelayServer"); } String updateText; String holiday = HolidayDatabase.getHoliday(true); String moonEffect = HolidayDatabase.getMoonEffect(); if (holiday.equals("")) { updateText = moonEffect; } else { updateText = holiday + ", " + moonEffect; } KoLmafia.updateDisplay(updateText); if (MailManager.hasNewMessages()) { KoLmafia.updateDisplay("You have new mail."); } }
private void solve(TimeStep step) { m_profile.solveInit = 0; m_profile.solveVelocity = 0; m_profile.solvePosition = 0; // Size the island for the worst case. island.init( m_bodyCount, m_contactManager.m_contactCount, m_jointCount, m_contactManager.m_contactListener); // Clear all the island flags. for (Body b = m_bodyList; b != null; b = b.m_next) { b.m_flags &= ~Body.e_islandFlag; } for (Contact c = m_contactManager.m_contactList; c != null; c = c.m_next) { c.m_flags &= ~Contact.ISLAND_FLAG; } for (Joint j = m_jointList; j != null; j = j.m_next) { j.m_islandFlag = false; } // Build and simulate all awake islands. int stackSize = m_bodyCount; if (stack.length < stackSize) { stack = new Body[stackSize]; } for (Body seed = m_bodyList; seed != null; seed = seed.m_next) { if ((seed.m_flags & Body.e_islandFlag) == Body.e_islandFlag) { continue; } if (seed.isAwake() == false || seed.isActive() == false) { continue; } // The seed can be dynamic or kinematic. if (seed.getType() == BodyType.STATIC) { continue; } // Reset island and stack. island.clear(); int stackCount = 0; stack[stackCount++] = seed; seed.m_flags |= Body.e_islandFlag; // Perform a depth first search (DFS) on the constraint graph. while (stackCount > 0) { // Grab the next body off the stack and add it to the island. Body b = stack[--stackCount]; assert (b.isActive() == true); island.add(b); // Make sure the body is awake. b.setAwake(true); // To keep islands as small as possible, we don't // propagate islands across static bodies. if (b.getType() == BodyType.STATIC) { continue; } // Search all contacts connected to this body. for (ContactEdge ce = b.m_contactList; ce != null; ce = ce.next) { Contact contact = ce.contact; // Has this contact already been added to an island? if ((contact.m_flags & Contact.ISLAND_FLAG) == Contact.ISLAND_FLAG) { continue; } // Is this contact solid and touching? if (contact.isEnabled() == false || contact.isTouching() == false) { continue; } // Skip sensors. boolean sensorA = contact.m_fixtureA.m_isSensor; boolean sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } island.add(contact); contact.m_flags |= Contact.ISLAND_FLAG; Body other = ce.other; // Was the other body already added to this island? if ((other.m_flags & Body.e_islandFlag) == Body.e_islandFlag) { continue; } assert (stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= Body.e_islandFlag; } // Search all joints connect to this body. for (JointEdge je = b.m_jointList; je != null; je = je.next) { if (je.joint.m_islandFlag == true) { continue; } Body other = je.other; // Don't simulate joints connected to inactive bodies. if (other.isActive() == false) { continue; } island.add(je.joint); je.joint.m_islandFlag = true; if ((other.m_flags & Body.e_islandFlag) == Body.e_islandFlag) { continue; } assert (stackCount < stackSize); stack[stackCount++] = other; other.m_flags |= Body.e_islandFlag; } } island.solve(islandProfile, step, m_gravity, m_allowSleep); m_profile.solveInit += islandProfile.solveInit; m_profile.solveVelocity += islandProfile.solveVelocity; m_profile.solvePosition += islandProfile.solvePosition; // Post solve cleanup. for (int i = 0; i < island.m_bodyCount; ++i) { // Allow static bodies to participate in other islands. Body b = island.m_bodies[i]; if (b.getType() == BodyType.STATIC) { b.m_flags &= ~Body.e_islandFlag; } } } broadphaseTimer.reset(); // Synchronize fixtures, check for out of range bodies. for (Body b = m_bodyList; b != null; b = b.getNext()) { // If a body was not in an island then it did not move. if ((b.m_flags & Body.e_islandFlag) == 0) { continue; } if (b.getType() == BodyType.STATIC) { continue; } // Update fixtures (for broad-phase). b.synchronizeFixtures(); } // Look for new contacts. m_contactManager.findNewContacts(); m_profile.broadphase = broadphaseTimer.getMilliseconds(); }
private void launch() { myContact = new ContactImpl(984, "Michael Jordan", "NBA legend"); output = 0; expected = 0; strOutput = ""; strExpected = ""; try { diary = new ContactManagerImpl(); pastMeetIds = new ArrayList<Integer>(); futMeetIds = new ArrayList<Integer>(); contactsGroup = new HashSet<Contact>(); aux = new HashSet<Contact>(); meetingDate = new GregorianCalendar(); contactsGroup.clear(); aux.clear(); } catch (Exception ex) { ex.printStackTrace(); } output = myContact.getId(); expected = 984; if (intExpected == intOutput) { System.out.println("TEST PASSED"); } else { System.out.println("TEST FAILED!"); } strOutput = myContact.getName(); strExpected = "Michael Jordan"; if (strExpected.equals(strOutput)) { System.out.println("TEST PASSED"); } else { System.out.println("TEST FAILED!"); } strOutput = myContact.getNotes(); strExpected = "NBA legend"; if (strExpected.equals(strOutput)) { System.out.println("TEST PASSED"); } else { System.out.println("TEST FAILED!"); } myContact.addNotes("Best shooting guard of all time"); strOutput = myContact.getNotes(); strExpected = "Best shooting guard of all time"; if (strExpected.equals(strOutput)) { System.out.println("TEST PASSED"); } else { System.out.println("TEST FAILED!"); } // add new contacts to the diary diary.addNewContact("Jamie O'Regan", "Best buddy"); diary.addNewContact("Travis Wallach", "MC"); diary.addNewContact("Wade Kelly", "Groomsman"); diary.addNewContact("Richard Barker", "Neighbour"); diary.addNewContact("Kate Crowne", "Family friend"); diary.addNewContact("Laura Edwards", "Girl friend"); diary.addNewContact("Willem Botha", "Squash Guru"); diary.addNewContact("Oli Callington", "Footie fiend"); diary.addNewContact("Tondi Busse", "DJ Baby Mumma Trouble"); diary.addNewContact("James Gill", "Pedal Juice Partner"); diary.addNewContact("James McLeod", "Law Consultant"); diary.addNewContact("Nicky Ho", "Interior Designer"); diary.addNewContact("Philippa Ho", "Dr"); diary.addNewContact("Matthew Swinson", "Jacky boy fan club"); diary.addNewContact("Dominic Leavy", "B52 bomber"); // build past meeting 1 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("Willem Botha"); contactsGroup.addAll(aux); aux = diary.getContacts("Oli Callington"); contactsGroup.addAll(aux); aux = diary.getContacts("Tondi Busse"); contactsGroup.addAll(aux); // set past date meetingDate.set(Calendar.YEAR, 2013); meetingDate.set(Calendar.MONTH, Calendar.JANUARY); meetingDate.set(Calendar.DAY_OF_MONTH, 28); // set past meeting 1; diary.addNewPastMeeting(contactsGroup, meetingDate, "Savoy Equity Awards Dinner"); // build past meeting 2 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("Willem Botha"); contactsGroup.addAll(aux); aux = diary.getContacts("Laura Edwards"); contactsGroup.addAll(aux); aux = diary.getContacts("Oli Callington"); contactsGroup.addAll(aux); // set past date meetingDate.set(Calendar.YEAR, 2014); meetingDate.set(Calendar.MONTH, Calendar.FEBRUARY); meetingDate.set(Calendar.DAY_OF_MONTH, 1); // set past meeting 2 diary.addNewPastMeeting(contactsGroup, meetingDate, "Dry January fall off wagon party"); // build past meeting 3 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("Richard Barker"); contactsGroup.addAll(aux); aux = diary.getContacts("Kate Crowne"); contactsGroup.addAll(aux); aux = diary.getContacts("Laura Edwards"); contactsGroup.addAll(aux); // set past date meetingDate.set(Calendar.YEAR, 2011); meetingDate.set(Calendar.MONTH, Calendar.JULY); meetingDate.set(Calendar.DAY_OF_MONTH, 14); // set past meeting 3; diary.addNewPastMeeting(contactsGroup, meetingDate, "Summer trip to the beach in 2011"); // build past meeting 4 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("Richard Barker"); contactsGroup.addAll(aux); aux = diary.getContacts("Matthew Swinson"); contactsGroup.addAll(aux); aux = diary.getContacts("Dominic Leavy"); contactsGroup.addAll(aux); // set past date meetingDate.set(Calendar.YEAR, 2013); meetingDate.set(Calendar.MONTH, Calendar.APRIL); meetingDate.set(Calendar.DAY_OF_MONTH, 11); // set past meeting 4; diary.addNewPastMeeting(contactsGroup, meetingDate, "Watched Football"); // add new past meetings to the pMeetIds list - could add this separately in the buildUp method? pastMeetIds = diary.getPastMeetingIdList(); // build future meeting 1 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("Jamie O'Regan"); contactsGroup.addAll(aux); aux = diary.getContacts("Travis Wallach"); contactsGroup.addAll(aux); aux = diary.getContacts("Wade Kelly"); contactsGroup.addAll(aux); // set future date meetingDate.set(Calendar.YEAR, 2014); meetingDate.set(Calendar.MONTH, Calendar.OCTOBER); meetingDate.set(Calendar.DAY_OF_MONTH, 31); // set future meeting 1 int id = diary.addFutureMeeting(contactsGroup, meetingDate); futMeetIds.add(id); // build future meeting 2 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("James Gill"); contactsGroup.addAll(aux); aux = diary.getContacts("James McLeod"); contactsGroup.addAll(aux); aux = diary.getContacts("Oli Callington"); contactsGroup.addAll(aux); // set future date meetingDate.set(Calendar.YEAR, 2014); meetingDate.set(Calendar.MONTH, Calendar.JUNE); meetingDate.set(Calendar.DAY_OF_MONTH, 21); // set future meeting 2 id = diary.addFutureMeeting(contactsGroup, meetingDate); futMeetIds.add(id); // build future meeting 3 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("Nicky Ho"); contactsGroup.addAll(aux); aux = diary.getContacts("Philippa Ho"); contactsGroup.addAll(aux); aux = diary.getContacts("Laura Edwards"); contactsGroup.addAll(aux); // set future date meetingDate.set(Calendar.YEAR, 2015); meetingDate.set(Calendar.MONTH, Calendar.SEPTEMBER); meetingDate.set(Calendar.DAY_OF_MONTH, 2); // set future meeting 3 id = diary.addFutureMeeting(contactsGroup, meetingDate); futMeetIds.add(id); // build future meeting 4 contactsGroup.clear(); aux.clear(); // set contact group aux = diary.getContacts("Philippa Ho"); contactsGroup.addAll(aux); aux = diary.getContacts("Matthew Swinson"); contactsGroup.addAll(aux); aux = diary.getContacts("Willem Botha"); contactsGroup.addAll(aux); // set future date meetingDate.set(Calendar.YEAR, 2016); meetingDate.set(Calendar.MONTH, Calendar.FEBRUARY); meetingDate.set(Calendar.DAY_OF_MONTH, 4); // set future meeting 4 id = diary.addFutureMeeting(contactsGroup, meetingDate); futMeetIds.add(id); diary.flush(); diary.readFile(); // System.out.println("*****decoded file******* MEETING SCHEDULE: " + // diary.getMeetingSchedule); // System.out.println("*****decoded file******* CONTACT SET: " + diary.getContactSet); // System.out.println("*****decoded file******* CONTACT LIST: " + diary.getContactList); }
/** * destroy a rigid body given a definition. No reference to the definition is retained. This * function is locked during callbacks. * * @warning This automatically deletes all associated shapes and joints. * @warning This function is locked during callbacks. * @param body */ public void destroyBody(Body body) { assert (m_bodyCount > 0); assert (isLocked() == false); if (isLocked()) { return; } // Delete the attached joints. JointEdge je = body.m_jointList; while (je != null) { JointEdge je0 = je; je = je.next; if (m_destructionListener != null) { m_destructionListener.sayGoodbye(je0.joint); } destroyJoint(je0.joint); body.m_jointList = je; } body.m_jointList = null; // Delete the attached contacts. ContactEdge ce = body.m_contactList; while (ce != null) { ContactEdge ce0 = ce; ce = ce.next; m_contactManager.destroy(ce0.contact); } body.m_contactList = null; Fixture f = body.m_fixtureList; while (f != null) { Fixture f0 = f; f = f.m_next; if (m_destructionListener != null) { m_destructionListener.sayGoodbye(f0); } f0.destroyProxies(m_contactManager.m_broadPhase); f0.destroy(); // TODO djm recycle fixtures (here or in that destroy method) body.m_fixtureList = f; body.m_fixtureCount -= 1; } body.m_fixtureList = null; body.m_fixtureCount = 0; // Remove world body list. if (body.m_prev != null) { body.m_prev.m_next = body.m_next; } if (body.m_next != null) { body.m_next.m_prev = body.m_prev; } if (body == m_bodyList) { m_bodyList = body.m_next; } --m_bodyCount; // TODO djm recycle body }
/** * Register a contact event listener. The listener is owned by you and must remain in scope. * * @param listener */ public void setContactListener(ContactListener listener) { m_contactManager.m_contactListener = listener; }
/** * Register a contact filter to provide specific control over collision. Otherwise the default * filter is used (_defaultFilter). The listener is owned by you and must remain in scope. * * @param filter */ public void setContactFilter(ContactFilter filter) { m_contactManager.m_contactFilter = filter; }
private void solveTOI(final TimeStep step) { final Island island = toiIsland; island.init( 2 * Settings.maxTOIContacts, Settings.maxTOIContacts, 0, m_contactManager.m_contactListener); if (m_stepComplete) { for (Body b = m_bodyList; b != null; b = b.m_next) { b.m_flags &= ~Body.e_islandFlag; b.m_sweep.alpha0 = 0.0f; } for (Contact c = m_contactManager.m_contactList; c != null; c = c.m_next) { // Invalidate TOI c.m_flags &= ~(Contact.TOI_FLAG | Contact.ISLAND_FLAG); c.m_toiCount = 0; c.m_toi = 1.0f; } } // Find TOI events and solve them. for (; ; ) { // Find the first TOI. Contact minContact = null; float minAlpha = 1.0f; for (Contact c = m_contactManager.m_contactList; c != null; c = c.m_next) { // Is this contact disabled? if (c.isEnabled() == false) { continue; } // Prevent excessive sub-stepping. if (c.m_toiCount > Settings.maxSubSteps) { continue; } float alpha = 1.0f; if ((c.m_flags & Contact.TOI_FLAG) != 0) { // This contact has a valid cached TOI. alpha = c.m_toi; } else { Fixture fA = c.getFixtureA(); Fixture fB = c.getFixtureB(); // Is there a sensor? if (fA.isSensor() || fB.isSensor()) { continue; } Body bA = fA.getBody(); Body bB = fB.getBody(); BodyType typeA = bA.m_type; BodyType typeB = bB.m_type; assert (typeA == BodyType.DYNAMIC || typeB == BodyType.DYNAMIC); boolean activeA = bA.isAwake() && typeA != BodyType.STATIC; boolean activeB = bB.isAwake() && typeB != BodyType.STATIC; // Is at least one body active (awake and dynamic or kinematic)? if (activeA == false && activeB == false) { continue; } boolean collideA = bA.isBullet() || typeA != BodyType.DYNAMIC; boolean collideB = bB.isBullet() || typeB != BodyType.DYNAMIC; // Are these two non-bullet dynamic bodies? if (collideA == false && collideB == false) { continue; } // Compute the TOI for this contact. // Put the sweeps onto the same time interval. float alpha0 = bA.m_sweep.alpha0; if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) { alpha0 = bB.m_sweep.alpha0; bA.m_sweep.advance(alpha0); } else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) { alpha0 = bA.m_sweep.alpha0; bB.m_sweep.advance(alpha0); } assert (alpha0 < 1.0f); int indexA = c.getChildIndexA(); int indexB = c.getChildIndexB(); // Compute the time of impact in interval [0, minTOI] final TOIInput input = toiInput; input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.sweepA.set(bA.m_sweep); input.sweepB.set(bB.m_sweep); input.tMax = 1.0f; pool.getTimeOfImpact().timeOfImpact(toiOutput, input); // Beta is the fraction of the remaining portion of the . float beta = toiOutput.t; if (toiOutput.state == TOIOutputState.TOUCHING) { alpha = MathUtils.min(alpha0 + (1.0f - alpha0) * beta, 1.0f); } else { alpha = 1.0f; } c.m_toi = alpha; c.m_flags |= Contact.TOI_FLAG; } if (alpha < minAlpha) { // This is the minimum TOI found so far. minContact = c; minAlpha = alpha; } } if (minContact == null || 1.0f - 10.0f * Settings.EPSILON < minAlpha) { // No more TOI events. Done! m_stepComplete = true; break; } // Advance the bodies to the TOI. Fixture fA = minContact.getFixtureA(); Fixture fB = minContact.getFixtureB(); Body bA = fA.getBody(); Body bB = fB.getBody(); backup1.set(bA.m_sweep); backup2.set(bB.m_sweep); bA.advance(minAlpha); bB.advance(minAlpha); // The TOI contact likely has some new contact points. minContact.update(m_contactManager.m_contactListener); minContact.m_flags &= ~Contact.TOI_FLAG; ++minContact.m_toiCount; // Is the contact solid? if (minContact.isEnabled() == false || minContact.isTouching() == false) { // Restore the sweeps. minContact.setEnabled(false); bA.m_sweep.set(backup1); bB.m_sweep.set(backup2); bA.synchronizeTransform(); bB.synchronizeTransform(); continue; } bA.setAwake(true); bB.setAwake(true); // Build the island island.clear(); island.add(bA); island.add(bB); island.add(minContact); bA.m_flags |= Body.e_islandFlag; bB.m_flags |= Body.e_islandFlag; minContact.m_flags |= Contact.ISLAND_FLAG; // Get contacts on bodyA and bodyB. tempBodies[0] = bA; tempBodies[1] = bB; for (int i = 0; i < 2; ++i) { Body body = tempBodies[i]; if (body.m_type == BodyType.DYNAMIC) { for (ContactEdge ce = body.m_contactList; ce != null; ce = ce.next) { if (island.m_bodyCount == island.m_bodyCapacity) { break; } if (island.m_contactCount == island.m_contactCapacity) { break; } Contact contact = ce.contact; // Has this contact already been added to the island? if ((contact.m_flags & Contact.ISLAND_FLAG) != 0) { continue; } // Only add static, kinematic, or bullet bodies. Body other = ce.other; if (other.m_type == BodyType.DYNAMIC && body.isBullet() == false && other.isBullet() == false) { continue; } // Skip sensors. boolean sensorA = contact.m_fixtureA.m_isSensor; boolean sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } // Tentatively advance the body to the TOI. backup1.set(other.m_sweep); if ((other.m_flags & Body.e_islandFlag) == 0) { other.advance(minAlpha); } // Update the contact points contact.update(m_contactManager.m_contactListener); // Was the contact disabled by the user? if (contact.isEnabled() == false) { other.m_sweep.set(backup1); other.synchronizeTransform(); continue; } // Are there contact points? if (contact.isTouching() == false) { other.m_sweep.set(backup1); other.synchronizeTransform(); continue; } // Add the contact to the island contact.m_flags |= Contact.ISLAND_FLAG; island.add(contact); // Has the other body already been added to the island? if ((other.m_flags & Body.e_islandFlag) != 0) { continue; } // Add the other body to the island. other.m_flags |= Body.e_islandFlag; if (other.m_type != BodyType.STATIC) { other.setAwake(true); } island.add(other); } } } subStep.dt = (1.0f - minAlpha) * step.dt; subStep.inv_dt = 1.0f / subStep.dt; subStep.dtRatio = 1.0f; subStep.positionIterations = 20; subStep.velocityIterations = step.velocityIterations; subStep.warmStarting = false; island.solveTOI(subStep, bA.m_islandIndex, bB.m_islandIndex); // Reset island flags and synchronize broad-phase proxies. for (int i = 0; i < island.m_bodyCount; ++i) { Body body = island.m_bodies[i]; body.m_flags &= ~Body.e_islandFlag; if (body.m_type != BodyType.DYNAMIC) { continue; } body.synchronizeFixtures(); // Invalidate all contact TOIs on this displaced body. for (ContactEdge ce = body.m_contactList; ce != null; ce = ce.next) { ce.contact.m_flags &= ~(Contact.TOI_FLAG | Contact.ISLAND_FLAG); } } // Commit fixture proxy movements to the broad-phase so that new contacts are created. // Also, some contacts can be destroyed. m_contactManager.findNewContacts(); if (m_subStepping) { m_stepComplete = false; break; } } }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Contact rnd = contactManager.getRandomContact(); return new ModelAndView("hello", "contact", rnd); }
/** * Overrides SubscriptionInitiator.handleInform(), defining what to do each time the DF is * modified by a contact Basically it adds/removes/updates contacts from ContactList according * to what has happened to DF. It also fires events on the GUI any time a view refresh is * needed. * * @param inform the message from DF containing a list of changes */ protected void handleInform(ACLMessage inform) { myLogger.log( Logger.FINE, "Thread " + Thread.currentThread().getId() + ": Notification received from DF"); ContactManager.getInstance().resetModifications(); try { DFAgentDescription[] results = DFService.decodeNotification(inform.getContent()); if (results.length > 0) { for (int i = 0; i < results.length; ++i) { DFAgentDescription dfd = results[i]; AID contactAID = dfd.getName(); // Do something only if the notification deals with an agent different from the current // one if (!contactAID.equals(myAgent.getAID())) { myLogger.log( Logger.INFO, "Thread " + Thread.currentThread().getId() + ":df says that agent " + myAgent.getAID().getLocalName() + " updates or registers"); Iterator serviceIter = dfd.getAllServices(); // Registered or updated if (serviceIter.hasNext()) { ServiceDescription serviceDesc = (ServiceDescription) serviceIter.next(); Iterator propertyIt = serviceDesc.getAllProperties(); Location loc = Helper.extractLocation(propertyIt); String phoneNum = contactAID.getLocalName(); ContactManager.getInstance().addOrUpdateOnlineContact(phoneNum, loc); } else { myLogger.log( Logger.INFO, "Thread " + Thread.currentThread().getId() + ":df says that agent " + myAgent.getAID().getLocalName() + " deregisters"); String phoneNumber = contactAID.getLocalName(); Contact c = ContactManager.getInstance().getContact(phoneNumber); ContactManager.getInstance().setContactOffline(phoneNumber); MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.CONTACT_DISCONNECT_EVENT); event.addParam(MsnEvent.CONTACT_DISCONNECT_PARAM_CONTACTNAME, c.getName()); MsnEventMgr.getInstance().fireEvent(event); } MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT); ContactListChanges changes = ContactManager.getInstance().getModifications(); Map<String, Contact> cMap = ContactManager.getInstance().getAllContacts(); Map<String, ContactLocation> cLocMap = ContactManager.getInstance().getAllContactLocations(); myLogger.log( Logger.FINE, "Thread " + Thread.currentThread().getId() + ":Adding to VIEW_REFRESH_EVENT this list of changes: " + changes.toString()); event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LISTOFCHANGES, changes); event.addParam(MsnEvent.VIEW_REFRESH_CONTACTSMAP, cMap); event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LOCATIONMAP, cLocMap); MsnEventMgr.getInstance().fireEvent(event); } } } } catch (Exception e) { myLogger.log(Logger.WARNING, "See printstack for Exception.", e); e.printStackTrace(); } }