Jump to content
  • 0

L2jfrozen rebirht system


Question

Posted

Hi all. Please help me with code rebirth.java in L2jFrozen. 

When i changing sub class and relog in the game, rebirth skills dont appear. On the main class everything is ok. Thank you. 

 

Code:

/*
 * L2jFrozen Project - www.l2jfrozen.com 
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.l2jfrozen.gameserver.model.entity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;

import org.apache.log4j.Logger;

import com.l2jfrozen.Config;
import com.l2jfrozen.gameserver.datatables.SkillTable;
import com.l2jfrozen.gameserver.datatables.sql.ItemTable;
import com.l2jfrozen.gameserver.datatables.xml.ExperienceData;
import com.l2jfrozen.gameserver.idfactory.BitSetIDFactory;
import com.l2jfrozen.gameserver.model.L2Skill;
import com.l2jfrozen.gameserver.model.actor.instance.L2ItemInstance;
import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance;
import com.l2jfrozen.gameserver.network.serverpackets.CreatureSay;
import com.l2jfrozen.gameserver.network.serverpackets.SocialAction;
import com.l2jfrozen.util.CloseUtil;
import com.l2jfrozen.util.database.DatabaseUtils;
import com.l2jfrozen.util.database.L2DatabaseFactory;

/**
 * <strong>This 'Custom Engine' was developed for L2J Forum Member 'sauron3256' on November 1st, 2008.</strong><br>
 * <br>
 * <strong>Quick Summary:</strong><br>
 * This engine will grant the player special bonus skills at the cost of reseting him to level 1.<br>
 * The -USER- can set up to X Rebirths, the skills received and their respective levels, and the item and price of each rebirth.<br>
 * PLAYER's information is stored in an SQL Db under the table name: REBIRTH_MANAGER.<br>
 * @author <strong>Beetle and Shyla</strong>
 */
public class L2Rebirth
{
    private static Logger LOGGER = Logger.getLogger(BitSetIDFactory.class);
    
    /** The current instance - static repeller. */
    private static L2Rebirth _instance = null;
    
    /** Basically, this will act as a cache so it doesnt have to read DB information on relog. */
    private final HashMap<Integer, Integer> _playersRebirthInfo = new HashMap<>();
    
    /**
     * Creates a new NON-STATIC instance.
     */
    private L2Rebirth()
    {
        // Do Nothing ^_-
    }
    
    /**
     * Receives the non-static instance of the RebirthManager.
     * @return single instance of L2Rebirth
     */
    public static L2Rebirth getInstance()
    {
        if (_instance == null)
        {
            _instance = new L2Rebirth();
        }
        return _instance;
    }
    
    /**
     * This is what it called from the Bypass Handler. (I think that's all thats needed here).
     * @param player the player
     * @param command the command
     */
    public void handleCommand(final L2PcInstance player, final String command)
    {
        if (command.startsWith("custom_rebirth_requestrebirth"))
        {
            displayRebirthWindow(player);
        }
        else if (command.startsWith("custom_rebirth_confirmrequest"))
        {
            requestRebirth(player);
        }
    }
    
    /**
     * Display's an HTML window with the Rebirth Options.
     * @param player the player
     */
    public void displayRebirthWindow(final L2PcInstance player)
    {
        try
        {
            final int currBirth = getRebirthLevel(player); // Returns the player's current birth level
            
            // Don't send html if player is already at max rebirth count.
            if (currBirth >= Config.REBIRTH_MAX)
            {
                player.sendMessage("You are currently at your maximum rebirth count!");
                return;
            }
            
            // Returns true if BASE CLASS is a mage.
            final boolean isMage = player.getBaseTemplate().classId.isMage();
            // Returns the skill based on next Birth and if isMage.
            L2Skill skill = getRebirthSkill((currBirth + 1), isMage);
            
            String icon = "" + skill.getId();// Returns the skill's id.
            
            // Incase the skill is only 3 digits.
            if (icon.length() < 4)
            {
                icon = "0" + icon;
            }
            
            skill = null;
            icon = null;
            
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * Checks to see if the player is eligible for a Rebirth, if so it grants it and stores information.
     * @param player the player
     */
    public void requestRebirth(final L2PcInstance player)
    {
        // Check to see if Rebirth is enabled to avoid hacks
        if (!Config.REBIRTH_ENABLE)
        {
            LOGGER.warn("[WARNING] Player " + player.getName() + " is trying to use rebirth system when it's disabled.");
            return;
        }
        
        // Check the player's level.
        if (player.getLevel() < Config.REBIRTH_MIN_LEVEL)
        {
            player.sendMessage("You do not meet the level requirement for a Rebirth!");
            return;
        }
        
        else if (player.isSubClassActive())
        {
            player.sendMessage("Please switch to your Main Class before attempting a Rebirth.");
            return;
        }
        
        final int currBirth = getRebirthLevel(player);
        int itemNeeded = 0;
        int itemAmount = 0;
        
        if (currBirth >= Config.REBIRTH_MAX)
        {
            player.sendMessage("You are currently at your maximum rebirth count!");
            return;
        }
        
        // Get the requirements
        int loopBirth = 0;
        for (final String readItems : Config.REBIRTH_ITEM_PRICE)
        {
            final String[] currItem = readItems.split(",");
            if (loopBirth == currBirth)
            {
                itemNeeded = Integer.parseInt(currItem[0]);
                itemAmount = Integer.parseInt(currItem[1]);
                break;
            }
            loopBirth++;
        }
        
        // Their is an item required
        if (itemNeeded != 0)
        {
            // Checks to see if player has required items, and takes them if so.
            if (!playerIsEligible(player, itemNeeded, itemAmount))
                return;
        }
        
        // Check and see if its the player's first Rebirth calling.
        final boolean firstBirth = currBirth == 0;
        // Player meets requirements and starts Rebirth Process.
        grantRebirth(player, (currBirth + 1), firstBirth);
    }
    
    /**
     * Physically rewards player and resets status to nothing.
     * @param player the player
     * @param newBirthCount the new birth count
     * @param firstBirth the first birth
     */
    public void grantRebirth(final L2PcInstance player, final int newBirthCount, final boolean firstBirth)
    {
        try
        {
            final double actual_hp = player.getCurrentHp();
            final double actual_cp = player.getCurrentCp();
            
            int max_level = ExperienceData.getInstance().getMaxLevel();
            
            if (player.isSubClassActive())
            {
                max_level = Config.MAX_SUBCLASS_LEVEL;
            }
            
            // Protections
            Integer returnToLevel = Config.REBIRTH_RETURN_TO_LEVEL;
            if (returnToLevel < 1)
                returnToLevel = 1;
            if (returnToLevel > max_level)
                returnToLevel = max_level;
            
            // Resets character to first class.
            player.setClassId(player.getBaseClass());
            
            player.broadcastUserInfo();
            
            final byte lvl = Byte.parseByte(returnToLevel + "");
            
            final long pXp = player.getStat().getExp();
            final long tXp = ExperienceData.getInstance().getExpForLevel(lvl);
            
            if (pXp > tXp)
            {
                player.getStat().removeExpAndSp(pXp - tXp, 0);
            }
            else if (pXp < tXp)
            {
                player.getStat().addExpAndSp(tXp - pXp, 0);
            }
            
            // Remove the player's current skills.
            for (final L2Skill skill : player.getAllSkills())
            {
                player.removeSkill(skill);
            }
            // Give players their eligible skills.
            player.giveAvailableSkills();
            
            // restore Hp-Mp-Cp
            player.setCurrentCp(actual_cp);
            player.setCurrentMp(player.getMaxMp());
            player.setCurrentHp(actual_hp);
            player.broadcastStatusUpdate();
            
            // Updates the player's information in the Character Database.
            player.store();
            
            if (firstBirth)
            {
                storePlayerBirth(player);
            }
            else
            {
                updatePlayerBirth(player, newBirthCount);
            }
            
            // Give the player his new Skills.
            grantRebirthSkills(player);
            
            // Displays a congratulation message to the player.
            displayCongrats(player);
            returnToLevel = null;
            
            // Update skill list
            player.sendSkillList();
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * Special effects when the player levels.
     * @param player the player
     */
    public void displayCongrats(final L2PcInstance player)
    {
        // Victory Social Action.
        player.setTarget(player);
        player.broadcastPacket(new SocialAction(player.getObjectId(), 3));
        player.sendMessage("Congratulations " + player.getName() + ". You have been REBORN!");
    }
    
    /**
     * Check and verify the player DOES have the item required for a request. Also, remove the item if he has.
     * @param player the player
     * @param itemId the item id
     * @param itemAmount the item amount
     * @return true, if successful
     */
    public boolean playerIsEligible(final L2PcInstance player, final int itemId, final int itemAmount)
    {
        String itemName = ItemTable.getInstance().getTemplate(itemId).getName();
        L2ItemInstance itemNeeded = player.getInventory().getItemByItemId(itemId);
        
        if (itemNeeded == null || itemNeeded.getCount() < itemAmount)
        {
            player.sendMessage("You need atleast " + itemAmount + "  [ " + itemName + " ] to request a Rebirth!");
            return false;
        }
        
        // Player has the required items, so we're going to take them!
        player.getInventory().destroyItemByItemId("Rebirth Engine", itemId, itemAmount, player, null);
        player.sendMessage("Removed " + itemAmount + " " + itemName + " from your inventory!");
        
        itemName = null;
        itemNeeded = null;
        
        return true;
    }
    
    /**
     * Gives the available Bonus Skills to the player.
     * @param player the player
     */
    public void grantRebirthSkills(final L2PcInstance player)
    {
        // returns the current Rebirth Level
        final int rebirthLevel = getRebirthLevel(player);
        // Returns true if BASE CLASS is a mage.
        final boolean isMage = player.getBaseTemplate().classId.isMage();
        
        // Simply return since no bonus skills are granted.
        if (rebirthLevel == 0)
            return;
        
        // Load the bonus skills unto the player.
        CreatureSay rebirthText = null;
        for (int i = 0; i < rebirthLevel; i++)
        {
            final L2Skill bonusSkill = getRebirthSkill((i + 1), isMage);
            player.addSkill(bonusSkill, false);
            
            // If you'd rather make it simple, simply comment this out and replace with a simple player.sendmessage();
            rebirthText = new CreatureSay(0, 18, "Rebirth Manager ", " Granted you [ " + bonusSkill.getName() + " ] level [ " + bonusSkill.getLevel() + " ]!");
            player.sendPacket(rebirthText);
        }
        
        rebirthText = null;
    }
    
    /**
     * Return the player's current Rebirth Level.
     * @param player the player
     * @return the rebirth level
     */
    public int getRebirthLevel(final L2PcInstance player)
    {
        final int playerId = player.getObjectId();
        
        if (_playersRebirthInfo.get(playerId) == null)
        {
            loadRebirthInfo(player);
        }
        
        return _playersRebirthInfo.get(playerId);
    }
    
    /**
     * Return the L2Skill the player is going to be rewarded.
     * @param rebirthLevel the rebirth level
     * @param mage the mage
     * @return the rebirth skill
     */
    public L2Skill getRebirthSkill(final int rebirthLevel, final boolean mage)
    {
        L2Skill skill = null;
        
        // Player is a Mage.
        if (mage)
        {
            int loopBirth = 0;
            for (final String readSkill : Config.REBIRTH_MAGE_SKILL)
            {
                final String[] currSkill = readSkill.split(",");
                if (loopBirth == (rebirthLevel - 1))
                {
                    skill = SkillTable.getInstance().getInfo(Integer.parseInt(currSkill[0]), Integer.parseInt(currSkill[1]));
                    break;
                }
                loopBirth++;
            }
        }
        // Player is a Fighter.
        else
        {
            int loopBirth = 0;
            for (final String readSkill : Config.REBIRTH_FIGHTER_SKILL)
            {
                final String[] currSkill = readSkill.split(",");
                if (loopBirth == (rebirthLevel - 1))
                {
                    skill = SkillTable.getInstance().getInfo(Integer.parseInt(currSkill[0]), Integer.parseInt(currSkill[1]));
                    break;
                }
                loopBirth++;
            }
        }
        return skill;
    }
    
    /**
     * Database caller to retrieve player's current Rebirth Level.
     * @param player the player
     */
    public void loadRebirthInfo(final L2PcInstance player)
    {
        final int playerId = player.getObjectId();
        int rebirthCount = 0;
        
        Connection con = null;
        try
        {
            ResultSet rset;
            con = L2DatabaseFactory.getInstance().getConnection(false);
            PreparedStatement statement = con.prepareStatement("SELECT * FROM `rebirth_manager` WHERE playerId = ?");
            statement.setInt(1, playerId);
            rset = statement.executeQuery();
            
            while (rset.next())
            {
                rebirthCount = rset.getInt("rebirthCount");
            }
            
            DatabaseUtils.close(rset);
            DatabaseUtils.close(statement);
            statement = null;
            rset = null;
            
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            CloseUtil.close(con);
            con = null;
        }
        _playersRebirthInfo.put(playerId, rebirthCount);
    }
    
    /**
     * Stores the player's information in the DB.
     * @param player the player
     */
    public void storePlayerBirth(final L2PcInstance player)
    {
        Connection con = null;
        try
        {
            con = L2DatabaseFactory.getInstance().getConnection(false);
            PreparedStatement statement = con.prepareStatement("INSERT INTO `rebirth_manager` (playerId,rebirthCount) VALUES (?,1)");
            statement.setInt(1, player.getObjectId());
            statement.execute();
            statement = null;
            
            _playersRebirthInfo.put(player.getObjectId(), 1);
            
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            CloseUtil.close(con);
            con = null;
        }
    }
    
    /**
     * Updates the player's information in the DB.
     * @param player the player
     * @param newRebirthCount the new rebirth count
     */
    public void updatePlayerBirth(final L2PcInstance player, final int newRebirthCount)
    {
        Connection con = null;
        try
        {
            final int playerId = player.getObjectId();
            
            con = L2DatabaseFactory.getInstance().getConnection(false);
            PreparedStatement statement = con.prepareStatement("UPDATE `rebirth_manager` SET rebirthCount = ? WHERE playerId = ?");
            statement.setInt(1, newRebirthCount);
            statement.setInt(2, playerId);
            statement.execute();
            statement = null;
            
            _playersRebirthInfo.put(playerId, newRebirthCount);
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            CloseUtil.close(con);
            con = null;
        }
    }
}

3 answers to this question

Recommended Posts

  • 0
Posted
44 minutes ago, Zake said:

There should be a method on l2pcinstance about temporary skills. You should check if there is a subclass restriction there.

This is all code, what i find about rebirth, in l2pcinstance. I understand the Java language very poorly, if possible, tell me where the error is here?  Thank you.

 

// Rebirth Caller - if player has any skills, they will be granted them.
        if (Config.REBIRTH_ENABLE)
            L2Rebirth.getInstance().grantRebirthSkills(this);
        
        broadcastPacket(new SocialAction(getObjectId(), 15));
        sendPacket(new SkillCoolTime(this));
        
        if (getClan() != null)
            getClan().broadcastToOnlineMembers(new PledgeShowMemberListUpdate(this));

 

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • Very nice and passionate effort. Good luck.
    • SX.ORG is a global proxy platform offering residential, mobile and datacenter IPs for SEO, web scraping, ad verification and multi-account management. It provides flexible IP rotation, precise geo-targeting, HTTP(S)/SOCKS5 support, API access and pay-as-you-go pricing based only on the traffic you use.
    • L2-IMBA — SEASON 2  Custom PvP / PvE Interlude · Every Class Playable BETA — LIVE NOW GRAND START — 11 September 2026, 20:00 GMT+2 https://l2-imba.com · https://discord.com/invite/jmhVpj8ySv ═══════════════════════════════════════ RATES & CORE SETTINGS ═══════════════════════════════════════ Chronicle — Interlude XP / SP — x45, level-adjusted curve Adena — x1 Max level — 90 Subclass — 1, to level 80 Starting hub — Giran Skills — Auto-learn, post-80 via custom trainers Loot — Auto-loot with low-value filtering Buffs — Extended duration, expanded slots, saved schemes Client limit — NO DUAL-BOXING, one client per player Automation — Built-in auto-farm with daily time limit Offline — Trading and crafting enabled Current beta configuration. Final values confirmed at launch sign-off. ═══════════════════════════════════════ All 31 third classes are developed to level 90 through five specialized trainers — there are no dead classes here. Tanks, daggers, archers, warriors, summoners, healers, buffers and crafters all have real post-80 progression and a role worth playing. Full PvE progression through ten farm zones, thirty-five themed encounters and eighteen tracked raids, feeding into gear-equalized Team vs Team and open-world PvP. This isn't a stat patch with a new name. L2-IMBA keeps the combat, classes and world of Interlude and builds a new endgame on top of it — new equipment branches, custom class development past level 80, purpose-built farm ecosystems, boss progression, crafting, and augmentation, all connected into one progression loop. Level and develop your class → choose an armor identity → clear themed farm content → collect materials and boss resources → craft and upgrade without abandoning your build → compete in equalized and open-world PvP → reach God's equipment. ═══════════════════════════════════════ ROLE MASTERY ARMOR ═══════════════════════════════════════ Starting at Dynasty, armor becomes a real build choice instead of a mandatory set everyone wears. Each armor type offers three role masteries plus a flexible Universal path — twelve paths per tier, sixty full-set configurations across the progression. The chest piece selects your mastery; a matching five-piece set activates it. HEAVY   Juggernaut — frontline wall, shield synergy, reflection   Spellbreaker — anti-magic fortress, spell disruption   Slayer — heavy armor turned offensive, vampiric sustain LIGHT   Bowmaster — ranged pressure, kiting, accuracy   Assassin — positional burst, blow reliability, dagger lethals   Berserker — high-risk carry, power rises as HP falls ROBE   Arcanist — rapid-fire critical casting   Invoker — high-impact nuking and debuffs   Oracle — dedicated healing and support Upgrade recipes preserve your chosen path through every tier: Dynasty → Zariche → Valakas → Cursed → God's The system is gear-driven, not class-locked. Build creatively. ═══════════════════════════════════════ LEVEL 90 CLASS DEVELOPMENT ═══════════════════════════════════════ Max level extended to 90. Five specialized trainers — Archer, Tank, Rogue, Warrior, Mystic — cover all 31 third classes in post-80 progression, with 470+ learning entries. Every race gets a custom passive from level one. Tanks get distinct Human/Elf/Dark Elf identities. Duelist gains a two-handed greatsword path. Fortune Seeker becomes a real fighter without losing its spoil identity. Maestro gets a durable frontline route. Summoners, cubics and servitors get deeper combat logic rather than stat scaling. This is backed by server-side combat work — dedicated handling for debuff proficiency, PvE skill damage, blows, lethals, bow reuse, vampirism and reflection. ═══════════════════════════════════════ THE FARMING WORLD ═══════════════════════════════════════ Ten dedicated farm destinations via Global Gatekeeper: Farm Coins 1 & 2, Holy, Fire/Water, Wind, Earth, Unholy, Golden, Chaotic and Night zones. Seven themed enemy families — Undead, Demon, Angel, Beast, Bug, Water, Fire — each with four stages and a mini-boss. Thirty-five distinct encounters, each with its own resource identity feeding crafting. Eighteen tracked raids — twelve Farm Raid Bosses and six Custom Epic Raid Bosses. Plus a scheduled group-based Party Zone with dynamically managed normal and rare spawns. ═══════════════════════════════════════ CRAFTING & ENDGAME ═══════════════════════════════════════ SOUL FORGE — recycle old weapons into tier resources, convert boss and farm materials, craft Legendary components. Old gear becomes input, not warehouse clutter. CURATED AUGMENTATION — data-driven Top-Grade and Legendary profiles with meaningful stat, active and passive pools. Active effects are categorized so the same effect can't be stacked through equipment swapping. EXTENDED ENCHANT — Custom Crystal and Legendary stages. On the Legendary route, a failed enchant does not destroy the item or reduce its enchant level. Long-term progression, not an all-or-nothing gamble. TREASURE CHESTS — Rare, Immortal, Epic and Legendary tiers feeding gear growth, crafting and augmentation. ═══════════════════════════════════════ PvP ═══════════════════════════════════════ Gear-equalized Team vs Team on a recurring schedule — your equipment is snapshotted and restored, so the fight is about play, not who farmed longest. Open-world PvP with rewards and ranks alongside it. ═══════════════════════════════════════ QUALITY OF LIFE ═══════════════════════════════════════ - No dual-boxing — one client per player, enforced - Built-in auto-farm with a daily time limit — no third-party software needed, and third-party automation is bannable - Auto-learn skills, auto-loot with low-value drop filtering - Extended-duration buffs, expanded slots, saved schemes - Offline trading and crafting - Global Gatekeeper, global class change - Offline combat automation disabled ═══════════════════════════════════════ BY THE NUMBERS ═══════════════════════════════════════ 380+ custom item definitions · 110+ weapons and shields · 210+ armor and wearables · 250+ custom skill definitions · 2,700+ custom monster placements · 90+ shop and exchange catalogs · 1,100+ offers ═══════════════════════════════════════ BETA ═══════════════════════════════════════ Core systems, progression identities and content routes are in place. Exact item bonuses, mastery values, skill strength, reuse times, augment pools, enchant chances, drop rates and crafting costs remain subject to testing. Beta changes will refine balance without removing the defining role of each mastery or the overall progression structure. All beta characters are wiped at full launch. Beta testers keep their rewards. ═══════════════════════════════════════ OPEN BETA — 4 SEPTEMBER 2026 · 18:00 GMT+2 Website: https://l2-imba.com Wiki: https://l2-imba.com/wiki Register: https://l2-imba.com/account Download: https://l2-imba.com/start-playing Discord:  https://discord.com/invite/jmhVpj8ySv
    • 🛡️ 100% Safe on your personal Gmail. Zero VPN required and works globally. Grab yours directly on klouditem.com!
  • Topics

×
×
  • Create New...

Important Information

This community uses essential cookies to function properly. Non-essential cookies and third-party services are used only with your consent. Read our Privacy Policy and We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue..