Exemplo n.º 1
0
class _ObjectDefinitionTested(CreationDataBase, HasTunableSingletonFactory,
                              AutoFactoryInit):
    FACTORY_TUNABLES = {
        'fallback_definition':
        TunableReference(
            description=
            '\n            Should no test pass, use this definition.\n            ',
            manager=services.definition_manager(),
            allow_none=True),
        'definitions':
        TunableList(
            description=
            '\n            A list of potential object definitions to use.\n            ',
            tunable=TunableTuple(
                weight=TunableMultiplier.TunableFactory(
                    description=
                    '\n                    The weight of this definition relative to other\n                    definitions in this list.\n                    '
                ),
                definition=TunableReference(
                    description=
                    '\n                    The definition of the object to be created.\n                    ',
                    manager=services.definition_manager(),
                    pack_safe=True)))
    }

    def get_definition(self, resolver):
        definition = weighted_random_item([
            (pair.weight.get_multiplier(resolver), pair.definition)
            for pair in self.definitions
        ])
        if definition is not None:
            return definition
        return self.fallback_definition
Exemplo n.º 2
0
def tuning_reload(_connection=None):
    sims4.callback_utils.invoke_callbacks(sims4.callback_utils.CallbackEvent.TUNING_CODE_RELOAD)
    done = set()
    dependents = set()
    for manager in get_managers().values():
        for changed in manager.get_changed_files():
            done.add(changed)
            new_dependents = manager.reload_by_key(changed)
            while new_dependents is not None:
                dependents.update(new_dependents)
    dependents.difference_update(done)
    while dependents:
        next_dependent = dependents.pop()
        done.add(next_dependent)
        next_type = next_dependent.type
        manager = services.get_instance_manager(next_type)
        new_dependents = manager.reload_by_key(next_dependent)
        while new_dependents is not None:
            new_dependents.difference_update(done)
            dependents.update(new_dependents)
            continue
    sims4.commands.output('Reloading definitions tags: Begin.', _connection)
    services.definition_manager().refresh_build_buy_tag_cache()
    sims4.commands.output('Reloading definitions tags: End.', _connection)
    sims4.commands.output('Reload done', _connection)
    return True
Exemplo n.º 3
0
def tuning_reload(_connection=None):
    if not paths.SUPPORT_RELOADING_RESOURCES:
        sims4.commands.output('Tuning reloading requires the --enable_tuning_reload flag.', _connection)
        return False
    if not paths.LOCAL_WORK_ENABLED:
        logger.warn("Attempting to reload tuning with 'ignore local work'. This is probably incorrect.")
    sims4.callback_utils.invoke_callbacks(sims4.callback_utils.CallbackEvent.TUNING_CODE_RELOAD)
    done = set()
    dependents = set()
    for manager in get_managers().values():
        for changed in manager.get_changed_files():
            done.add(changed)
            new_dependents = manager.reload_by_key(changed)
            if new_dependents is not None:
                dependents.update(new_dependents)
    dependents.difference_update(done)
    while dependents:
        next_dependent = dependents.pop()
        done.add(next_dependent)
        next_type = next_dependent.type
        manager = services.get_instance_manager(next_type)
        new_dependents = manager.reload_by_key(next_dependent)
        if new_dependents is not None:
            new_dependents.difference_update(done)
            dependents.update(new_dependents)
    sims4.commands.output('Reloading definitions tags: Begin.', _connection)
    services.definition_manager().refresh_build_buy_tag_cache()
    sims4.commands.output('Reloading definitions tags: End.', _connection)
    sims4.commands.output('Refreshing cached localwork.', _connection)
    sims4.resources.cache_localwork()
    sims4.commands.output('Reload done', _connection)
    return True
Exemplo n.º 4
0
class FishingData(HasTunableSingletonFactory, AutoFactoryInit):
    FACTORY_TUNABLES = {
        'weight_fish':
        TunableMultiplier.TunableFactory(
            description=
            '\n            A tunable list of tests and multipliers to apply to the weight \n            used to determine if the Sim will catch a fish instead of treasure \n            or junk. This will be used in conjunction with the Weight Junk and \n            Weight Treasure.\n            '
        ),
        'weight_junk':
        TunableMultiplier.TunableFactory(
            description=
            '\n            A tunable list of tests and multipliers to apply to the weight\n            used to determine if the Sim will catch junk instead of a fish or \n            treasure. This will be used in conjunction with the Weight Fish and \n            Weight Treasure.\n            '
        ),
        'weight_treasure':
        TunableMultiplier.TunableFactory(
            description=
            '\n            A tunable list of tests and multipliers to apply to the weight\n            used to determine if the Sim will catch a treasure instead of fish \n            or junk. This will be used in conjunction with the Weight Fish and \n            Weight Junk.\n            '
        ),
        'possible_treasures':
        TunableList(
            description=
            "\n            If the Sim catches a treasure, we'll pick one of these based on their weights.\n            Higher weighted treasures have a higher chance of being caught.\n            ",
            tunable=TunableTuple(treasure=TunableReference(
                manager=services.definition_manager(), pack_safe=True),
                                 weight=TunableMultiplier.TunableFactory())),
        'possible_fish':
        TunableList(
            description=
            "\n            If the Sim catches a fish, we'll pick one of these based on their weights.\n            Higher weighted fish have a higher chance of being caught.\n            ",
            tunable=TunableTuple(fish=TunableReference(
                manager=services.definition_manager(), pack_safe=True),
                                 weight=TunableMultiplier.TunableFactory()),
            minlength=1)
    }

    def _verify_tuning_callback(self):
        import fishing.fish_object
        for fish in self.possible_fish:
            if not issubclass(fish.fish.cls, fishing.fish_object.Fish):
                logger.error(
                    "Possible Fish on Fishing Data has been tuned but there either isn't a definition tuned for the fish, or the definition currently tuned is not a Fish.\n{}",
                    self)

    def get_possible_fish_gen(self):
        yield from self.possible_fish

    def choose_fish(self, resolver, require_bait=True):
        weighted_fish = [
            (f.weight.get_multiplier(resolver), f.fish)
            for f in self.possible_fish
            if f.fish.cls.can_catch(resolver, require_bait=require_bait)
        ]
        if weighted_fish:
            return sims4.random.weighted_random_item(weighted_fish)

    def choose_treasure(self, resolver):
        weighted_treasures = [(t.weight.get_multiplier(resolver), t.treasure)
                              for t in self.possible_treasures]
        if weighted_treasures:
            return sims4.random.weighted_random_item(weighted_treasures)
Exemplo n.º 5
0
class ChefTuning:
    CHEF_STATION_POT_OBJECT = TunablePackSafeReference(
        description=
        "\n        The pot object to create at the chef's station.\n        ",
        manager=services.definition_manager())
    CHEF_STATION_PAN_OBJECT = TunablePackSafeReference(
        description=
        "\n        The pan object to create at the chef's station.\n        ",
        manager=services.definition_manager())
    CHEF_STATION_CUTTING_BOARD_OBJECT = TunablePackSafeReference(
        description=
        "\n        The cutting board object to create at the chef's station.\n        ",
        manager=services.definition_manager())
    CHEF_STATION_PAN_SLOT = Tunable(
        description=
        '\n        The name of the slot in which the pan object should be placed.\n        ',
        tunable_type=str,
        default='_ctnm_SimInteraction_1')
    CHEF_STATION_POT_SLOT = Tunable(
        description=
        '\n        The name of the slot in which the pot object should be placed.\n        ',
        tunable_type=str,
        default='_ctnm_SimInteraction_2')
    CHEF_STATION_CUTTING_BOARD_SLOT = Tunable(
        description=
        '\n        The name of the slot in which the cutting board object should be placed.\n        ',
        tunable_type=str,
        default='_ctnm_SimInteraction_4')
    CHEF_STATION_SERVE_SLOT_TYPE = TunableReference(
        description=
        '\n        The slot type of the serve slots on the chef station.\n        ',
        manager=services.get_instance_manager(sims4.resources.Types.SLOT_TYPE))
    CHEF_STATION_SERVING_PLATTER_OBJECT = TunablePackSafeReference(
        description=
        "\n        The serving platter object the chef will create and place when they're\n        done cooking an order.\n        ",
        manager=services.definition_manager())
    CHEF_HAS_ORDER_BUFF = TunablePackSafeReference(
        description=
        '\n        The buff a chef should get when they have an order. This should drive\n        them to do the active cooking animations.\n        ',
        manager=services.buff_manager())
    CHEF_COMPLIMENT_LOOT = LootActions.TunablePackSafeReference(
        description=
        "\n        The loot action to trigger when a customer compliments a chef. This\n        won't happen until the waitstaff deliver the compliment.\n        \n        The customer Sim will be the Actor and the Chef will be TargetSim.\n        "
    )
    CHEF_INSULT_LOOT = LootActions.TunablePackSafeReference(
        description=
        "\n        The loot action to trigger when a customer insults a chef. This won't\n        happen until the waitstaff deliver the insult.\n        \n        The customer Sim will be the Actor and the Chef will be TargetSim.\n        "
    )
    PICK_UP_ORDER_INTERACTION = TunablePackSafeReference(
        description=
        '\n        The interaction the sim will run when they pick their order up from the\n        Chef Station. This is only used when a Sim places an order directly at\n        the chef station.\n        ',
        manager=services.get_instance_manager(
            sims4.resources.Types.INTERACTION))
Exemplo n.º 6
0
 def list_pack_safe(list_pack_safe=False):
     tuning_name = 'fallback_vehicle_def'
     description = "\n            The definition of the vehicle to spawn if the sim doesn't have\n            a favorite vehicle.\n        "
     if list_pack_safe:
         return {
             tuning_name:
             TunableReference(description=description,
                              manager=services.definition_manager(),
                              pack_safe=True)
         }
     return {
         tuning_name:
         TunablePackSafeReference(description=description,
                                  manager=services.definition_manager())
     }
Exemplo n.º 7
0
 def get_beach_locator_definition():
     if OceanTuning.beach_locator_definition is None:
         for definition in services.definition_manager(
         ).get_definitions_for_tags_gen((OceanTuning.BEACH_LOCATOR_TAG, )):
             OceanTuning.beach_locator_definition = definition
             break
     return OceanTuning.beach_locator_definition
Exemplo n.º 8
0
class TempleRoomData(HasTunableSingletonFactory, AutoFactoryInit):
    FACTORY_TUNABLES = {
        'gate':
        TunableSet(
            description=
            '\n            A set of states in which the gate in this room can potentially\n            start.\n            ',
            tunable=TunableReference(
                description=
                '\n                A potential starting state for the gate in this room.\n                ',
                manager=services.get_instance_manager(
                    sims4.resources.Types.OBJECT_STATE),
                class_restrictions=('ObjectStateValue', ))),
        'traps':
        TunableMapping(
            description=
            '\n            A mapping of trap objects to the interactions that can be used in\n            the pool potential of "trigger" interaction. A trap object will be\n            chosen at random from this mapping and placed at each placeholder\n            trap in this room. Once all trap objects have been chosen and placed\n            for a room, all of the mapped interactions will be collected and one\n            random interaction will be chosen as the "trigger" interaction.\n            ',
            key_name='Trap',
            key_type=TunableReference(
                description=
                '\n                A reference to the trap object.\n                ',
                manager=services.definition_manager()),
            value_name='Potential Trigger Interactions',
            value_type=TunableSet(
                description=
                '\n                A set of interactions that, if successfully completed on the\n                chosen trap object, will trigger the loot for the gate in this\n                room.\n                ',
                tunable=TunableReference(
                    description=
                    '\n                    One of the potential trigger interactions. This interaction\n                    also needs to be tuned on the object chosen for this trap.\n                    ',
                    manager=services.get_instance_manager(
                        sims4.resources.Types.INTERACTION),
                    class_restrictions=('SuperInteraction', ))))
    }
def purchase_to_inventory(inventory_obj, def_id:str=None, mailman_purchase:bool=False, _connection=None):
    definition_manager = services.definition_manager()
    definition = definition_manager.get(def_id)
    if definition is None:
        return False
    client = services.client_manager().get(_connection)
    if client is None:
        return False
    household = client.household
    price = definition.price
    if household.funds.money < price:
        return False
    if mailman_purchase:
        obj = services.active_lot().create_object_in_hidden_inventory(definition)
    else:
        inventory = inventory_obj.get_target().inventory_component
        if inventory is None:
            return False
        obj = create_object(definition)
        if obj is None:
            return False
        if not inventory.player_try_add_object(obj):
            obj.destroy(source=inventory, cause='Failed to purchase object into inventory')
            return False
    obj.set_household_owner_id(household.id)
    obj.try_post_bb_fixup(force_fixup=True, active_household_id=services.active_household_id())
    household.funds.remove(price, Consts_pb2.TELEMETRY_OBJECT_BUY)
    return True
Exemplo n.º 10
0
def create_all_carryables(_connection=None):
    carryable_component_name = 'carryable'
    done = False
    created_objs = []
    obj_ids = []
    try:
        definition_manager = services.definition_manager()
        for obj_def in definition_manager.loaded_definitions:
            obj_tuning = obj_def.cls
            carryable_component = obj_tuning._components.get(
                carryable_component_name)
            if carryable_component is None:
                pass
            try:
                obj = objects.system.create_object(obj_def)
            except:
                obj = None
            if obj is not None:
                created_objs.append(obj)
                obj_ids.append(obj.id)
            while done:
                break
        create_multiple_objects(1, _connection=_connection, *obj_ids)
    finally:
        for obj in created_objs:
            obj.destroy(
                source=obj,
                cause='Destroying original objects in create_all_carryables.')
Exemplo n.º 11
0
 def _verify_tunable_callback(instance_class, tunable_name, source, value):
     if value.apply_definition:
         original_definition = services.definition_manager().find_first_definition_by_cls(instance_class)
         if original_definition is not None:
             (result, error) = original_definition.is_similar(value.definition, ignore_rig_footprint=True)
             if not result:
                 logger.error("<{}>'s client state model swap requires a definition change {} which is incompatible with its own definition {}.\n {}", instance_class.__name__, value.definition, original_definition, error, owner='cjiang')
Exemplo n.º 12
0
class ItemCost(ItemCostBase, AutoFactoryInit, HasTunableSingletonFactory):
    UNAVAILABLE_TOOLTIP_HEADER = TunableLocalizedStringFactory(
        description=
        '\n        A string to be used as a header for a bulleted list of items that the\n        Sim is missing in order to run this interaction.\n        '
    )
    AVAILABLE_TOOLTIP_HEADER = TunableLocalizedStringFactory(
        description=
        '\n        A string to be used as a header for a bulleted list of items that the\n        Sim will consume in order to run this interaction.\n        '
    )
    FACTORY_TUNABLES = {
        'ingredients':
        TunableList(
            description=
            '\n            List of tuples of Objects and Quantity, which will indicate\n            the cost of items for this interaction to run\n            ',
            tunable=TunableTuple(
                description=
                '\n                Pair of Object and Quantity needed for this interaction\n                ',
                ingredient=TunableReference(
                    description=
                    '\n                    Object reference of the type of game object needed.\n                    ',
                    manager=services.definition_manager()),
                quantity=TunableRange(
                    description=
                    '\n                    Quantity of objects needed\n                    ',
                    tunable_type=int,
                    default=1,
                    minimum=1),
                missing_ingredient_additional_text=OptionalTunable(
                    description=
                    '\n                    If set, this text is inserted on a new line following a missing ingredient.\n                    ',
                    tunable=TunableLocalizedString(
                        default=None,
                        description='The string key of the text description'
                    ))))
    }
Exemplo n.º 13
0
def purchase_to_inventory(inventory_obj,
                          def_id: str = None,
                          mailman_purchase: bool = False,
                          _connection=None):
    definition_manager = services.definition_manager()
    definition = definition_manager.get(def_id)
    if definition is None:
        return False
    client = services.client_manager().get(_connection)
    if client is None:
        return False
    household = client.household
    price = definition.price
    if household.funds.money < price:
        return False
    if mailman_purchase:
        obj = services.active_lot().create_object_in_hidden_inventory(
            definition)
    else:
        inventory = inventory_obj.get_target().inventory_component
        if inventory is None:
            return False
        obj = create_object(definition)
        if obj is None:
            return False
        if not inventory.player_try_add_object(obj):
            obj.destroy(source=inventory,
                        cause='Failed to purchase object into inventory')
            return False
    obj.set_household_owner_id(household.id)
    obj.try_post_bb_fixup(force_fixup=True,
                          active_household_id=services.active_household_id())
    household.funds.remove(price, Consts_pb2.TELEMETRY_OBJECT_BUY)
    return True
Exemplo n.º 14
0
class SocialJigFromDefinition(AutoFactoryInit, HasTunableSingletonFactory):
    FACTORY_TUNABLES = {
        'jig_definition':
        TunableReference(
            description=
            '\n            The jig to use for finding a place to do the social.\n            ',
            manager=services.definition_manager())
    }

    def get_transforms_gen(self,
                           actor,
                           target,
                           actor_slot_index=0,
                           target_slot_index=1,
                           stay_outside=False,
                           fallback_routing_surface=None,
                           **kwargs):
        (actor_transform, target_transform,
         routing_surface) = fgl_and_get_two_person_transforms_for_jig(
             self.jig_definition,
             actor,
             actor_slot_index,
             target,
             target_slot_index,
             stay_outside,
             fallback_routing_surface=fallback_routing_surface,
             **kwargs)
        yield (actor_transform, target_transform, routing_surface, ())

    def get_footprint_polygon(self, sim_a, sim_b, sim_a_transform,
                              sim_b_transform, routing_surface):
        return placement.get_placement_footprint_compound_polygon(
            sim_b_transform.translation, sim_b_transform.orientation,
            routing_surface, self.jig_definition.get_footprint(0))
Exemplo n.º 15
0
class FishingBait(HasTunableSingletonFactory, AutoFactoryInit):
    FACTORY_TUNABLES = {
        'bait_name':
        TunableLocalizedStringFactory(
            description='\n            Name of fishing bait.\n            '),
        'bait_description':
        TunableLocalizedStringFactory(
            description=
            '\n            Description of fishing bait.\n            '),
        'bait_icon_definition':
        TunableReference(
            description=
            '\n            Object definition that will be used to render icon of fishing bait.\n            ',
            manager=services.definition_manager()),
        'bait_buff':
        TunableReference(
            description='\n            Buff of fishing bait.\n            ',
            manager=services.buff_manager()),
        'bait_priority':
        TunableRange(
            description=
            '\n            The priority of the bait. When an object can be categorized into\n            multiple fishing bait categories, the highest priority category \n            will be chosen.\n            ',
            tunable_type=int,
            default=1,
            minimum=1)
    }
 def __init__(self, **kwargs):
     super().__init__(definition=TunableReference(
         description=
         '\n                The definition of the object.\n                ',
         manager=services.definition_manager(),
         **kwargs),
                      verify_tunable_callback=ObjectDefinition.
                      verify_tunable_callback)
Exemplo n.º 17
0
 def get_definition(pack_safe):
     return {
         'object_definition':
         TunableReference(
             description=
             '\n                The definition of the object to be created.\n                ',
             manager=services.definition_manager(),
             pack_safe=pack_safe)
     }
Exemplo n.º 18
0
 def __init__(self, definition, tuned_native_components=frozendict(), **kwargs):
     super().__init__()
     self.id = 0
     self.manager = None
     self.definition = definition
     self._visible_to_client = False
     self._interaction_refs = None
     self._parts = None
     self.content_source = ContentSource.DEFAULT
     self.wall_or_fence_placement = self._has_placement_flag(build_buy.PlacementFlags.WALL_GRAPH_PLACEMENT)
     if definition is not None:
         services.definition_manager().register_definition(definition.id, self)
         for component_id in definition.components:
             comp = objects.components.native_component_id_to_class[component_id]
             if not comp.has_server_component():
                 continue
             factory = getattr(tuned_native_components, comp.CNAME, None) or comp.create_component
             self.add_component(factory(self))
Exemplo n.º 19
0
 def ingredient_override(pack_safe=False):
     return {
         'ingredient_ref':
         TunableReference(
             description=
             '\n                Reference to ingredient object definition.\n                Example: gardenFruitGENOnion_01\n                ',
             manager=services.definition_manager(),
             pack_safe=pack_safe)
     }
Exemplo n.º 20
0
 def load(self, persistable_data):
     definition_manager = services.definition_manager()
     gardening_component_data = persistable_data.Extensions[
         protocols.PersistableGardeningComponent.persistable_data]
     for fruit_spawner in gardening_component_data.fruit_spawners:
         definition = definition_manager.get(fruit_spawner.definition_id)
         if definition is None:
             continue
         self._add_spawner(definition)
Exemplo n.º 21
0
 def apply_definition(self, definition, obj_state=0):
     if not isinstance(definition, objects.definition.Definition):
         definition = services.definition_manager().get(definition)
     self._model = definition.get_model(obj_state)
     self._material_variant = definition.material_variant
     self._rig = definition.get_rig(obj_state)
     self._slot = definition.get_slot(obj_state)
     self._slots_resource = definition.get_slots_resource(obj_state)
     self._state_index = obj_state
Exemplo n.º 22
0
    def __call__(self, sim):
        def _abort(vehicle_obj):
            sim.allow_opacity_change = True
            sim.fade_in()
            if vehicle_obj is not None:
                vehicle_obj.destroy()

        vehicle = None
        if sim.sim_info.favorites_tracker is not None:
            favorites_tracker = sim.sim_info.favorites_tracker
            definition_manager = services.definition_manager()
            vehicle_def_id = favorites_tracker.get_favorite_definition_id(
                self.vehicle_obj_tag)
            if vehicle_def_id is not None:
                vehicle_def = definition_manager.get(vehicle_def_id)
                if vehicle_def is not None:
                    vehicle = objects.system.create_object(vehicle_def)
        if vehicle is None:
            if self.fallback_vehicle_def is None:
                _abort(vehicle)
                return True
            vehicle = create_object(self.fallback_vehicle_def)
            if vehicle is None:
                _abort(vehicle)
                return True
        vehicle.set_household_owner_id(sim.household_id)
        starting_location = placement.create_starting_location(
            position=sim.position)
        fgl_context = placement.create_fgl_context_for_object(
            starting_location, vehicle)
        (position, orientation) = placement.find_good_location(fgl_context)
        if position is None or orientation is None:
            _abort(vehicle)
            return True
        vehicle.transform = sims4.math.Transform(position, orientation)
        result = vehicle.vehicle_component.push_drive_affordance(
            sim, priority=Priority.Critical)
        if result is None:
            _abort(vehicle)
            return True
        if result.interaction is None:
            logger.warn(
                "Vehicle's push drive affordance {} resulted in a None interaction. Result: {}.",
                vehicle.vehicle_component.drive_affordance,
                result,
                owner='jmorrow')
            _abort(vehicle)
            return True
        sim.fade_in()
        vehicle.claim()
        for situation in services.get_zone_situation_manager().get_all():
            if sim in situation.all_sims_in_situation_gen():
                situation.manage_vehicle(vehicle)
                break
        return True
Exemplo n.º 23
0
 def get_definition(self, resolver):
     definition_manager = services.definition_manager()
     filtered_defs = list(
         definition_manager.get_definitions_for_tags_gen(self.filter_tags))
     if len(filtered_defs) > 0:
         return random.choice(filtered_defs)
     logger.error(
         '{} create object basic extra tries to find object definitions tagged as {} , but no object definitions were found.',
         resolver,
         self.filter_tags,
         owner='jgiordano')
 def load(self, persistable_data):
     definition_manager = services.definition_manager()
     gardening_component_data = persistable_data.Extensions[protocols.PersistableGardeningComponent.persistable_data]
     for fruit_spawner in gardening_component_data.fruit_spawners:
         spawner_data = FruitSpawnerData()
         definition = definition_manager.get(fruit_spawner.definition_id)
         spawner_data.set_fruit(definition)
         self._fruit_spawners.append(spawner_data)
         self.owner.add_spawner_data(spawner_data)
     if GardeningTuning.is_spliced(self.owner):
         tree_fruit_names = self.root_stock_name_list
         self._spliced_description = GardeningTuning.get_spliced_description(tree_fruit_names)
Exemplo n.º 25
0
def dump_definition(guid, _connection=None):
    manager = services.definition_manager()
    obj_def = manager.get(guid)
    if not obj_def:
        sims4.commands.output(
            'DUMP_DEFINITION: Unknown object definition GUID {}.'.format(guid),
            _connection)
    else:
        sims4.commands.output('Definition {}'.format(guid), _connection)
        for (key, value) in vars(obj_def).items():
            sims4.commands.output('    {} = {}'.format(key, value),
                                  _connection)
Exemplo n.º 26
0
class TraitToDefinitionPickerInteraction(ObjectDefinitionPickerInteraction):
    INSTANCE_TUNABLES = {
        'trait_to_definition_id':
        TunableMapping(
            description=
            '\n            Backward mapping of trait to what umbrella the sim carries\n            ',
            key_type=Trait.TunableReference(
                description=
                '\n                Trait to look for\n                '),
            value_type=TunableReference(
                description=
                '\n                The object must have this definition.\n                ',
                manager=services.definition_manager())),
        'disabled_toolip':
        TunableLocalizedStringFactory(
            description=
            '\n            Tooltip that displays if the sim currently has the trait in the mapping.\n            '
        )
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._selected_definition_id = None

    def _create_dialog(self, owner, target_sim=None, target=None, **kwargs):
        traits_to_find = self.trait_to_definition_id.keys()
        for trait in traits_to_find:
            if not owner.has_trait(trait):
                continue
            self._selected_definition_id = self.trait_to_definition_id[trait]
            break
        return super()._create_dialog(owner,
                                      target_sim=target_sim,
                                      target=target,
                                      **kwargs)

    @flexmethod
    def create_row(cls, inst, row_obj, context=DEFAULT, target=DEFAULT):
        inst_or_cls = inst if inst is not None else cls
        is_disabled = inst_or_cls._selected_definition_id is not None and row_obj.id == inst_or_cls._selected_definition_id.id
        icon_info = IconInfoData(obj_def_id=row_obj.id,
                                 obj_geo_hash=row_obj.thumbnail_geo_state_hash,
                                 obj_material_hash=row_obj.material_variant)
        row = ObjectPickerRow(
            object_id=row_obj.id,
            def_id=row_obj.id,
            icon_info=icon_info,
            tag=row_obj,
            is_enable=not is_disabled,
            row_tooltip=inst_or_cls.disabled_toolip if is_disabled else None,
            name=LocalizationHelperTuning.get_object_name(row_obj))
        inst_or_cls._test_continuation(row, context=context, target=target)
        return row
Exemplo n.º 27
0
 def __init__(self,
              definition,
              tuned_native_components=frozendict(),
              **kwargs):
     super().__init__()
     self.id = 0
     self.manager = None
     self.definition = definition
     self.visible_to_client = False
     self.interaction_refs = set()
     if definition is not None:
         services.definition_manager().register_definition(
             definition.id, self)
         for component_id in definition.components:
             comp = objects.components.native_component_id_to_class[
                 component_id]
             if not comp.has_server_component():
                 pass
             factory = tuned_native_components.get(
                 comp.CNAME) or comp.create_component
             self.add_component(factory(self))
 def get_definition_notebook_data(self, ingredient_cache=()):
     definition_manager = services.definition_manager()
     fruit_definition = definition_manager.get(
         self.entry_object_definition_id)
     if fruit_definition is None:
         return
     gardening_tuned_values = fruit_definition.cls._components.gardening._tuned_values
     plant_definition = gardening_tuned_values.plant
     sub_list_data = []
     sub_list_data.append(
         SubListData(None, 0, 0, True, False,
                     self.entry_text_value(fruit_definition.price / 5),
                     None, None))
     season_service = services.season_service()
     if season_service is not None:
         season_text = GardeningTuning.get_seasonality_text_from_plant(
             plant_definition)
         if season_text is None:
             season_text = GardeningTuning.PLANT_SEASONALITY_TEXT(
                 GardeningTuning.SEASONALITY_ALL_SEASONS_TEXT)
         sub_list_data.append(
             SubListData(None, 0, 0, True, False, season_text, None, None))
     sub_list_data.append(
         SubListData(
             None, 0, 0, True, False,
             LocalizationHelperTuning.get_object_description(
                 plant_definition), None, None))
     for (splice_fruit, splice_fruit_result
          ) in gardening_tuned_values.splicing_recipies.items():
         sub_list_data.append(
             SubListData(
                 None, 0, 0, True, False,
                 self.entry_text_splicing(splice_fruit,
                                          splice_fruit_result), None, None))
     gardening_collection_data = ObjectCollectionData.get_collection_data(
         CollectionIdentifier.Gardening)
     for obj_data in itertools.chain(
             gardening_collection_data.object_list,
             gardening_collection_data.bonus_object_list):
         if obj_data.collectable_item is fruit_definition:
             rarity_text = ObjectCollectionData.COLLECTION_RARITY_MAPPING[
                 obj_data.rarity].text_value
             sub_list_data.append(
                 SubListData(None, 0, 0, True, False,
                             self.entry_text_rarity(rarity_text), None,
                             None))
             break
     entry_data = EntryData(
         LocalizationHelperTuning.get_object_name(fruit_definition),
         IconInfoData(obj_def_id=fruit_definition.id), None, sub_list_data,
         None)
     return entry_data
Exemplo n.º 29
0
 def get_definition(self, *_, **__):
     if not self._recorded_trend_tag:
         return TrendTuning.TRENDLESS_VIDEO_DEFINITION
     definition_manager = services.definition_manager()
     filtered_defs = list(
         definition_manager.get_definitions_for_tags_gen(
             {self._recorded_trend_tag}))
     if not filtered_defs:
         logger.error(
             'Could not find object definitions tagged as {} for recording trends.',
             self.filter_tags)
         return
     return random.choice(filtered_defs)
Exemplo n.º 30
0
def create_script_object(definition_or_id, obj_state=0, **kwargs):
    from objects.definition import Definition
    if isinstance(definition_or_id, Definition):
        definition = definition_or_id
    else:
        definition = services.definition_manager().get(definition_or_id,
                                                       obj_state=obj_state)
        if definition is None:
            logger.error(
                'Unable to create a script object for definition id: {0}',
                definition_or_id)
            return
    return definition.instantiate(obj_state=obj_state, **kwargs)
Exemplo n.º 31
0
class _ObjectDefinition(CreationDataBase, HasTunableSingletonFactory,
                        AutoFactoryInit):
    FACTORY_TUNABLES = {
        'definition':
        TunableReference(
            description=
            '\n            The definition of the object that is created.\n            ',
            manager=services.definition_manager(),
            pack_safe=True)
    }

    def get_definition(self, resolver):
        return self.definition
class TerrainService(sims4.service_manager.Service):
    __qualname__ = 'TerrainService'
    TERRAIN_DEFINITION = TunableReference(
        description=
        '\n        The definition used to instantiate the Terrain object.\n        ',
        manager=services.definition_manager(),
        class_restrictions='Terrain')

    def start(self):
        create_terrain_object()
        return True

    def stop(self):
        destroy_terrain_object()
Exemplo n.º 33
0
def create_script_object(definition_or_id, consume_exceptions=True, obj_state=0, **kwargs):
    from objects.definition import Definition
    if isinstance(definition_or_id, Definition):
        definition = definition_or_id
    else:
        try:
            definition = services.definition_manager().get(definition_or_id, obj_state=obj_state)
        except:
            logger.exception('Unable to create a script object for definition id: {0}', definition_or_id)
            if consume_exceptions:
                return
            raise
    zone_id = get_zone_id(can_be_none=True)
    if zone_id is not None and not build_buy.can_create_object(zone_id, 0, 1):
        logger.warn('Fire code said this object could not be created. -Mike Duke')
        return
    return definition.instantiate(obj_state=obj_state, **kwargs)
Exemplo n.º 34
0
def purchase_picker_response(inventory_target, mailman_purchase:bool=False, *def_ids_and_amounts, _connection=None):
    total_price = 0
    current_purchased = 0
    objects_to_buy = []
    definition_manager = services.definition_manager()
    for (def_id, amount) in zip(def_ids_and_amounts[::2], def_ids_and_amounts[1::2]):
        definition = definition_manager.get(def_id)
        if definition is None:
            sims4.commands.output('inventory.purchase_picker_response: Definition not found with id {}'.format(def_id), _connection)
            return False
        purchase_price = definition.price*amount
        total_price += purchase_price
        objects_to_buy.append((definition, amount))
    client = services.client_manager().get(_connection)
    if client is None:
        sims4.commands.output('inventory.purchase_picker_response: No client found to make purchase.', _connection)
        return False
    household = client.household
    if household.funds.money < total_price:
        sims4.commands.output('inventory.purchase_picker_response: Insufficient funds for household to purchase items.', _connection)
        return False
    if mailman_purchase:
        inventory = services.active_lot().get_hidden_inventory()
    else:
        inventory_owner = inventory_target.get_target()
        inventory = inventory_owner.inventory_component
    if inventory is None:
        sims4.commands.output('inventory.purchase_picker_response: Inventory not found for items to be purchased into.', _connection)
        return False
    for (definition, amount) in objects_to_buy:
        obj = create_object(definition)
        if obj is None:
            sims4.commands.output('inventory.purchase_picker_response: Failed to create object with definition {}.'.format(definition), _connection)
        obj.set_stack_count(amount)
        if not inventory.player_try_add_object(obj):
            sims4.commands.output('inventory.purchase_picker_response: Failed to add object into inventory: {}'.format(obj), _connection)
            obj.destroy(source=inventory, cause='inventory.purchase_picker_response: Failed to add object into inventory.')
        obj.set_household_owner_id(household.id)
        obj.try_post_bb_fixup(force_fixup=True, active_household_id=services.active_household_id())
        purchase_price = definition.price*amount
        current_purchased += purchase_price
    household.funds.remove(current_purchased, Consts_pb2.TELEMETRY_OBJECT_BUY)
    return True
Exemplo n.º 35
0
 def __init__(self, **kwargs):
     super().__init__(collection_id=TunableEnumEntry(description='\n                            Unique Id for this collectible, cannot be re-used.\n                            ', tunable_type=CollectionIdentifier, default=CollectionIdentifier.Unindentified, export_modes=ExportModes.All), collection_name=TunableLocalizedString(description='\n                            Localization String For the name of the \n                            collection.  This will be read on the collection\n                            UI to separate each item group.\n                            ', export_modes=ExportModes.All), completed_award=TunableReference(description='\n                            Object award when the collection is completed.  \n                            This is an object that will be awarded to the Sim\n                            when all the items inside a collection have been \n                            discovered.\n                            ', manager=services.definition_manager(), export_modes=ExportModes.All), completed_award_money=TunableRange(description='\n                            Money award when the collection is completed.  \n                            ', tunable_type=int, default=100, minimum=0, export_modes=ExportModes.All), completed_award_notification=UiDialogNotification.TunableFactory(description='\n                            Notification that will be shown when the collection\n                            is completed and the completed_award is given.\n                            '), object_list=TunableList(description='\n                            List of object that belong to a collectible group.\n                            ', tunable=CollectibleTuple.TunableFactory(), export_modes=ExportModes.All), screen_slam=OptionalTunable(description='\n                             Screen slam to show when the collection is\n                             completed and the completed_award is given.\n                             Localization Tokens: Collection Name = {0.String}\n                             ', tunable=ui.screen_slam.TunableScreenSlamSnippet()), first_collected_notification=OptionalTunable(description='\n                            If enabled a notification will be displayed when\n                            the first item of this collection has been found.\n                            ', tunable=UiDialogNotification.TunableFactory(description='\n                                Notification that will be shown the first item of\n                                this collection has been found.\n                                '), disabled_name='No_notification', enabled_name='Display_notification'))
Exemplo n.º 36
0
from objects.definition import Definition
from protocolbuffers.Localization_pb2 import LocalizedString
from sims4.localization import TunableLocalizedString
from sims4.tuning.instances import TunedInstanceMetaclass
from sims4.tuning.tunable import TunableList, TunableReference, Tunable, TunableBlock, TunableWallPattern, TunableRailing, TunableStairs, TunableCeilingRail, TunableFloorPattern, TunableFloorTrim, TunableRoofPattern, TunableRoofTrim, TunableStyle, TunableFence, TunableRoof, TunableFrieze
import services
import sims4.commands
interaction_manager = services.get_instance_manager(sims4.resources.Types.INTERACTION)
object_manager = services.definition_manager()

class Constants:
    __qualname__ = 'Constants'

    class LocalizationStrings:
        __qualname__ = 'Constants.LocalizationStrings'
        CHIPS = TunableLocalizedString(description='UI Dialog option for fridge snack')
        COMEDY = TunableLocalizedString(description="UI dialog option for 'comedy' TV channel")
        FRENCH_TOAST = TunableLocalizedString(description="UI Dialog option for 'french toast' fridge crafting option")
        JUICE = TunableLocalizedString(description='UI Dialog option for one-handed potable fridge snack')
        JUICEDRINK2 = TunableLocalizedString(description='UI Dialog option for a specific juicedrink type drink crafting station option')
        MAKE_CHEESECAKE = TunableLocalizedString(description='Recipe interaction name for cheesecake')
        MAKE_FRENCH_TOAST = TunableLocalizedString(description='Recipe interaction name for french toast')
        MAKE_JUICEDRINK_GENERIC = TunableLocalizedString(description='Prototype name for make generic juice-type drink interaction from a crafting station')
        MAKE_JUICEDRINK2 = TunableLocalizedString(description='Recipe interaction name for a specific juicedrink-type drink that can be crafted')
        MAKE_ROAST_CHICKEN = TunableLocalizedString(description='Recipe interaction name for roast chicken')
        ONE_HANDED_DRINK = TunableLocalizedString(description='\n            UI Dialog option for fridge snack.\n            A one-handed drink available to newly created families that is compatible with foods.')
        ONE_HANDED_SNACK = TunableLocalizedString(description='\n            UI Dialog option for fridge snack.\n            A one-handed food available to newly created families that is compatible with drinks.\n            Also pushes the eat at table interaction from the fridge.')
        ROAST_CHICKEN = TunableLocalizedString(description="UI Dialog option for 'roast chicken' fridge crafting option")
        SIMCITY_CHEESECAKE = TunableLocalizedString(description="UI Dialog option for 'cheesecake' fridge crafting option")
        TOGETHER_MODIFIER = TunableLocalizedString(description="\n            Pie Menu Dialog modifier for doing a thing 'Together'.\n            For example, Go Here Together, or Jog Here Together")
Exemplo n.º 37
0
                                                display_name
                                                ='Whitelist Items'),
                exclude_affordances=TunableList(AffordanceReference,
                                                display_name
                                                ='Filter Exception Items'),
                include_lists=TunableList(
                    TunableAffordanceListReference(),
                    display_name='Whitelist Lists'),
                exclude_lists=TunableList(
                    TunableAffordanceListReference(),
                    display_name='Filter Exception Lists'),
                locked_args={'include_all_by_default': False},
                description=
                '\n                        This will create incompatibility with all interactions by\n                        default, except those that are whitelisted, from which you\n                        can define exceptions.'),
            default='include_all',
            description=
            '\n                    This defines the default compatibility with other interactions.'),
                         description=description,
                         needs_tuning=True,
                         **kwargs)


(TunableAffordanceFilterReference,
 TunableAffordanceFilterSnippet) = define_snippet(AFFORDANCE_FILTER,
                                                  _TunableAffordanceFilter)
(TunableColorReference, TunableColorSnippet) = define_snippet(COLOR,
                                                              TunableColor())
(TunableObjectListReference, TunableObjectListSnippet) = define_snippet(
    OBJECT_LIST,
    TunableList(TunableReference(manager=services.definition_manager())))
Exemplo n.º 38
0
    def __init__(self, description='A model state.', **kwargs):

        def validate_definition_swap(instance_class, tunable_name, source, value):
            pass

        super().__init__(model=TunableResourceKey(description='\n                The model file resource key.\n                ', default=None, resource_types=(sims4.resources.Types.MODEL,)), model_from_definition=TunableTuple(definition=TunableReference(description='\n                    The model definition.\n                    ', manager=services.definition_manager()), also_swap_definition=Tunable(description='\n                    If True, the model swap operation will also swap the\n                    definition for the object. If false it will only change the\n                    model. We should only set this to True for sculpture\n                    objects.\n                    ', tunable_type=bool, default=False)), description=description, callback=validate_definition_swap, **kwargs)
Exemplo n.º 39
0
def generate_slot_type_data(*args, zone_id:int=None, **kwargs):
    slot_type_data = []
    for (key, slot_type) in services.get_instance_manager(sims4.resources.Types.SLOT_TYPE).types.items():
        data = {}
        data['slot_type_name'] = slot_type.__name__
        data['slot_type_name_hash'] = key.instance
        data['slot_type_name_hashx'] = hex(key.instance)
        if slot_type._bone_name is not None:
            data['bone_name'] = slot_type._bone_name
            data['bone_name_hash'] = slot_type.bone_name_hash
            data['bone_name_hashx'] = hex(slot_type.bone_name_hash)
        data['slot_type_sets'] = []
        for (key, slot_type_set) in services.get_instance_manager(sims4.resources.Types.SLOT_TYPE_SET).types.items():
            while slot_type in slot_type_set.slot_types:
                sub_data = {}
                sub_data['name'] = slot_type_set.__name__
                data['slot_type_sets'].append(sub_data)
        data['objects'] = []
        data['object_slots'] = []
        for ((def_id, obj_state), definition) in services.definition_manager()._definitions_cache.items():
            slot_types = set()
            slot_types.update(DecorativeSlotTuning.get_slot_types_for_object(get_object_decosize(definition.id)))
            try:
                def_slot_type_set_key = get_object_slotset(def_id)
                def_slot_type_set = get_slot_type_set_from_key(def_slot_type_set_key)
                while def_slot_type_set is not None:
                    slot_types.update(def_slot_type_set.slot_types)
            except:
                pass
            if slot_type in slot_types:
                sub_data = {}
                sub_data['id'] = '{}[{}]'.format(def_id, obj_state)
                sub_data['tuning_id'] = definition.tuning_file_id
                if definition.cls is not None:
                    sub_data['object_name'] = definition.cls.__name__
                data['objects'].append(sub_data)
            slots_resource = definition.get_slots_resource(obj_state)
            while slots_resource is not None:
                slot_infos = []
                for (slot_name_hash, slot_types) in SlotComponent.get_containment_slot_infos_static(slots_resource, definition.get_rig(obj_state), None):
                    while slot_type in slot_types:
                        try:
                            slot_infos.append((native.animation.get_joint_name_for_hash_from_rig(definition.get_rig(obj_state), slot_name_hash), slot_name_hash, hex(slot_name_hash)))
                        except:
                            pass
                if slot_infos:
                    slot_infos.sort()

                    def info_list(i):
                        return ', '.join(str(e[i]) for e in slot_infos)

                    sub_data = {}
                    sub_data['id'] = '{}[{}]'.format(def_id, obj_state)
                    sub_data['tuning_id'] = definition.tuning_file_id
                    if definition.cls is not None:
                        sub_data['object_name'] = definition.cls.__name__
                    sub_data['bone_name'] = info_list(0)
                    sub_data['bone_name_hash'] = info_list(1)
                    sub_data['bone_name_hashx'] = info_list(2)
                    data['object_slots'].append(sub_data)
        slot_type_data.append(data)
    return slot_type_data
Exemplo n.º 40
0
 def __init__(self, **kwargs):
     super().__init__(TunableReference(description='\n                The definition of the object.\n                ', manager=services.definition_manager()), **kwargs)
Exemplo n.º 41
0
 def __init__(self, optional_create=True, description='An object definition and states to apply.', class_restrictions=(), **kwargs):
     definition = TunableReference(description='\n            An object to create.', manager=services.definition_manager(), class_restrictions=class_restrictions)
     if optional_create:
         definition = OptionalTunable(definition)
     super().__init__(definition=definition, carry_track=OptionalTunable(description='\n                Which hand to carry the object in.', tunable=TunableEnumEntry(PostureTrack, default=PostureTrack.RIGHT)), initial_states=TunableList(description='\n                A list of states to apply to the finished object as soon as it is created.\n                ', tunable=TunableStateValueReference()), apply_states=TunableList(description='\n                A list of states to apply to the finished object.\n                ', tunable=TunableStateValueReference()), apply_tags=TunableSet(description='\n                A list of category tags to apply to the finished product.\n                ', tunable=TunableEnumEntry(tag.Tag, tag.Tag.INVALID, description='What tag to test for')), conditional_apply_states=TunableList(description='\n                A list of states to apply to the finished object based on if the associated test passes.\n                ', tunable=TunableTuple(description='\n                    The test to pass for the given state to be applied.', test=TunableTestVariant(), state=TunableStateValueReference())), super_affordances=TunableList(description='\n                Affordances available on the finished product.\n                ', tunable=SuperInteraction.TunableReference()), loot_list=TunableList(description='\n                A list of pre-defined loot operations to apply after crafting object creation.\n                ', tunable=LootActions.TunableReference()), quality_adjustment=TunableQualityInfo(), simoleon_value_modifiers_map=TunableMapping(description='\n                    The mapping of state values to Simolean value modifiers.\n                    The final value of a craftable is decided based on its\n                    retail value multiplied by the sum of all modifiers for\n                    states that apply to the final product. All modifiers are\n                    added together first, then the sum will be multiplied by\n                    the retail price.\n                    ', key_type=TunableStateValueReference(description='\n                        The quality state values. If this item has this state,\n                        then a random modifier between min_value and max_value\n                        will be multiplied to the retail price.'), value_type=TunableInterval(description='\n                        The maximum modifier multiplied to the retail price based on the provided state value\n                        ', tunable_type=float, default_lower=1, default_upper=1)), simoleon_value_skill_curve=TunableStatisticModifierCurve.TunableFactory(description="\n                Allows you to adjust the final value of the object based on the Sim's\n                level of a given skill.\n                ", axis_name_overrides=('Skill Level', 'Simoleon Multiplier'), locked_args={'subject': ParticipantType.Actor}), masterworks=OptionalTunable(TunableTuple(description='\n                    If the result of this recipe can be a masterwork (i.e. a\n                    masterpiece for paintings), this should be enabled.\n                    ', base_test=event_testing.tests.TunableTestSet(description="\n                        This is the initial gate for a recipe to result in a masterwork.\n                        If this test doesn't pass, we don't even attempt to be a masterwork.\n                        "), base_chance=Tunable(description='\n                        Once the Base Test passes, this will be the base chance\n                        that this recipe will result in a masterwork.\n                        0.0 is 0% chance\n                        1.0 is 100% chance\n                        ', tunable_type=float, default=0.25), multiplier_tests=TunableList(TunableTuple(description='\n                        When deciding if this recipe will result in a masterwork, we run through each test in this list. IF the test passes, its multiplier will be applied to the Base Chance.\n                        ', multiplier=Tunable(description='\n                            This is the multiplier that will be applied to the Base Chance if these tests pass.\n                            ', tunable_type=float, default=1), tests=event_testing.tests.TunableTestSet())), skill_adjustment=Tunable(description="\n                        The masterwork chance adjustment based on the effective skill\n                        level. For each level higher than the requires skill of the recipe,\n                        the masterwork chance will be increased by this.\n                        There is no penalty if, somehow, the required skill is greater\n                        than the effective skill of the Sim.\n                        Example:\n                        Assume you're level 10 writing skill and you're crafting a\n                        book that requires level 4 writing skill. Also assume skill_adjustment\n                        is tuned to 0.05 and the base_chance is set to 0.25.\n                        The differences in skill is 10 (your skill) - 4 (required skill) = 6 \n                        Then, take this difference, 6 * 0.05 (skill_adjustment) = 0.3\n                        The base chance, 0.25 + 0.3 = 0.55. 55% chance of this being a masterwork.\n                        ", tunable_type=float, default=0.0), simoleon_value_multiplier=TunableInterval(description='\n                        The amount by which the final simoleon value of the object will be multiplied if it is a masterwork.\n                        The multiplier is a random number between the lower and upper bounds, inclusively.\n                        ', tunable_type=float, default_lower=1, default_upper=1))), thumbnail_geo_state=OptionalTunable(description='\n                The geo state name override for recipe picker thumbnail generation.\n                ', disabled_name='UseCatalog', enabled_name='CustomValue', tunable=Tunable(description='Geo State name', tunable_type=str, default='')), thumbnail_material_state=OptionalTunable(description='\n                The material state name override for recipe picker thumbnail generation.\n                ', disabled_name='UseCatalog', enabled_name='CustomValue', tunable=Tunable(description='Material State name', tunable_type=str, default='')), description=description, **kwargs)
 def __init__(self, **kwargs):
     super().__init__(ingredient_ref=TunableReference(services.definition_manager(), description='Reference to ingredient object.'), description='This option uses an object definition as an individual ingredient.', **kwargs)