nickmaster24

Barn Storge System

Mar 22nd, 2015
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 26.53 KB | None | 0 0
  1. ResourceModule = require(game.ReplicatedStorage.ResourceModule)
  2. CatalogModule = require(game.ReplicatedStorage.CatalogModule)
  3.  
  4. --[[ INFO DATA SAVING FORMAT
  5.   [KEY] = INFO_{USER_ID}
  6.   [1] = Username (Updates every save)
  7.   [2] = Table of all usernames saved to the barn (Constant accross all regions)
  8.   [3] = Table of all resources saved in the barn (Constant accross all regions)
  9.   [4] = Table of all saved regions (FULL NAME eg. Region_{USER_ID}_1 )
  10.    
  11. ]]
  12.  
  13. --[[ OBJECT DATA SAVING FORMAT
  14.   [1] = Object Name (Integer pulled from a dictionary table)
  15.   [2] = X value of position
  16.         Terrain is flat so we don't need the Y value of position
  17.   [3] = Z value of position
  18.   [4] = Rotation (Objects only rotate on 1 axis in increments of 90 degrees)
  19.   [5] = Age (Can be nil)
  20.   [6] = Table of any additional data (Can be nil)
  21. ]]
  22.  
  23. --Fun code for later!
  24. function splitString(str, delim, maxNb)
  25.     -- Eliminate bad cases...
  26.     if string.find(str, delim) == nil then
  27.         return { str }
  28.     end
  29.     if maxNb == nil or maxNb < 1 then
  30.         maxNb = 0    -- No limit
  31.     end
  32.     local result = {}
  33.     local pat = "(.-)" .. delim .. "()"
  34.     local nb = 0
  35.     local lastPos
  36.     for part, pos in string.gmatch(str, pat) do
  37.         nb = nb + 1
  38.         result[nb] = part
  39.         lastPos = pos
  40.         if nb == maxNb then break end
  41.     end
  42.     -- Handle the last field
  43.     if nb ~= maxNb then
  44.         result[nb + 1] = string.sub(str, lastPos)
  45.     end
  46.     return result
  47. end
  48.  
  49. local NameForIntegerIndex = { --This is going to get really messy with more plants and objects  :(
  50.     Grass = 0,
  51.    
  52.     YoungSapling = 1,
  53.     OldSapling = 2,
  54.    
  55.     Wheat = 3,
  56.     Corn = 4,
  57.     Lettuce = 5,
  58.    
  59.     YoungTree = 6,
  60.     SmallTree = 7,
  61.     MediumTree = 8,
  62.     LargeTree = 9,
  63.     OldTree = 10,
  64.    
  65.     SmallRock = 11,
  66.     MediumRock = 12,
  67.     LargeRock = 13,
  68.    
  69.     WoodHut = 14,
  70.     WoodFence = 15,
  71.     PlankFence = 16,
  72.     StoneFence = 17,
  73.     StonePath = 18,
  74.     Torch = 19,
  75.     Sprinkler = 20,
  76.    
  77.     HugeRock = 21,
  78.     SmallPond = 22,
  79.     FirePit = 23,
  80.    
  81.     Potato = 24,
  82.     TomatoBush = 25,
  83.    
  84.     CowSet = 26,
  85.     SheepSet = 27,
  86.    
  87.     GoldPile = 28,
  88.     StonePile = 29,
  89.     PotatoStand = 30,
  90.     TomatoStand = 31,
  91.     LettuceStand = 32,
  92.    
  93.     PigSet = 33,
  94.    
  95.     Generator = 34,
  96.     AnimalReactor = 35,
  97.     FlourMill = 36,
  98.    
  99.     Carrot = 37,
  100.    
  101.     Outhouse = 38,
  102.     WoodenGate = 39,
  103.    
  104. }
  105.  
  106. local IntegerForNameIndex = {}
  107.     for k, v in pairs(NameForIntegerIndex) do
  108.         IntegerForNameIndex[v] = k
  109.     end
  110.  
  111. local GW = game.Workspace --Makes below easier; don't use other places so code stays readable
  112. local IntegerForLocationIndex = {}
  113. IntegerForLocationIndex[0] = GW.GrassStorage --lol never used
  114.  
  115. IntegerForLocationIndex[1] = GW.SaplingStorage
  116. IntegerForLocationIndex[2] = GW.SaplingStorage
  117.  
  118. IntegerForLocationIndex[3] = GW.CropStorage
  119. IntegerForLocationIndex[4] = GW.CropStorage
  120. IntegerForLocationIndex[5] = GW.CropStorage
  121.  
  122. IntegerForLocationIndex[6] = GW.TreeStorage
  123. IntegerForLocationIndex[7] = GW.TreeStorage
  124. IntegerForLocationIndex[8] = GW.TreeStorage
  125. IntegerForLocationIndex[9] = GW.TreeStorage
  126. IntegerForLocationIndex[10] = GW.TreeStorage
  127.  
  128.  
  129. IntegerForLocationIndex[11] = GW.RockStorage
  130. IntegerForLocationIndex[12] = GW.RockStorage
  131. IntegerForLocationIndex[13] = GW.RockStorage
  132.  
  133. IntegerForLocationIndex[14] = GW.StaticStorage
  134. IntegerForLocationIndex[15] = GW.StaticStorage
  135. IntegerForLocationIndex[16] = GW.StaticStorage
  136. IntegerForLocationIndex[17] = GW.StaticStorage
  137. IntegerForLocationIndex[18] = GW.StaticStorage
  138. IntegerForLocationIndex[19] = GW.StaticStorage
  139. IntegerForLocationIndex[20] = GW.StaticStorage
  140. IntegerForLocationIndex[21] = GW.StaticStorage
  141. IntegerForLocationIndex[22] = GW.StaticStorage
  142. IntegerForLocationIndex[23] = GW.StaticStorage
  143.  
  144. IntegerForLocationIndex[24] = GW.CropStorage
  145. IntegerForLocationIndex[25] = GW.CropStorage
  146.  
  147. IntegerForLocationIndex[26] = GW.StaticStorage
  148. IntegerForLocationIndex[27] = GW.StaticStorage
  149.  
  150. IntegerForLocationIndex[28] = GW.StaticStorage
  151. IntegerForLocationIndex[29] = GW.StaticStorage
  152. IntegerForLocationIndex[30] = GW.StaticStorage
  153. IntegerForLocationIndex[31] = GW.StaticStorage
  154. IntegerForLocationIndex[32] = GW.StaticStorage
  155.  
  156. IntegerForLocationIndex[33] = GW.StaticStorage
  157.  
  158. IntegerForLocationIndex[34] = GW.DynamicStorage
  159. IntegerForLocationIndex[35] = GW.StaticStorage
  160. IntegerForLocationIndex[36] = GW.DynamicStorage
  161.  
  162. IntegerForLocationIndex[37] = GW.CropStorage
  163.  
  164. IntegerForLocationIndex[38] = GW.StaticStorage
  165. IntegerForLocationIndex[39] = GW.StaticStorage
  166.  
  167. local RegionDataStore = game:GetService("DataStoreService"):GetDataStore("RegionStorage") --WE ARE LIVE :D :D :D :D
  168.  
  169. local CurrentPlayerData = { } --So we don't have to constantly call the player info files
  170.  
  171. function loadPlayerData( Player ) --Actual player passed
  172.     if( Player )then
  173.         local PlayerData  = nil
  174.         local good = pcall( function()
  175.             playerData = RegionDataStore:GetAsync( "INFO_" .. Player.userId )
  176.             end)
  177.         if( playerData )then
  178.             return playerData
  179.         elseif( good )then --Time to make new template data
  180.             playerData = {}
  181.             playerData[1] = Player.Name
  182.             playerData[2] = {}
  183.             playerData[3] = {}
  184.             playerData[4] = {}
  185.             return playerData
  186.         end    
  187.     end
  188.     if( Player )then
  189.         Player:kick("Critical Data Error")
  190.     end
  191.     return nil --This means something went very wrong
  192. end
  193.  
  194. function updatePlayerData( Player, Barn )
  195.     if( Player and Barn )then --I sure hope they exist
  196.         local PlayerData = CurrentPlayerData[ Player.userId ]
  197.         PlayerData[2] = { }
  198.         for _, v in pairs(Barn.Control.Players:getChildren())do
  199.             table.insert(PlayerData[2], v.Value)
  200.         end
  201.        
  202.         for _, v in pairs(Barn.Control.Resources:getChildren())do
  203.             PlayerData[3][v.Name] = v.Value
  204.         end
  205.        
  206.         local good = pcall( function()
  207.             RegionDataStore:SetAsync( "INFO_" .. Player.userId, PlayerData )
  208.         end )
  209.         if( not good )then
  210.             print("BAD BAD BAD BAD @updatePlayerData")
  211.         end
  212.     end
  213. end
  214.  
  215.  
  216. --Not used for some reason
  217. function savePlayerData( Player )
  218.     if( Player and CurrentPlayerData[ Player.userId ] )then
  219.         local good = pcall( function()
  220.             RegionDataStore:SetAsync( "INFO_" .. Player.userId, CurrentPlayerData[ Player.userId ] )
  221.         end )
  222.         if( not good )then
  223.             print("BAD BAD BAD BAD @savePlayerData")
  224.         end
  225.     end
  226. end
  227.  
  228.  
  229. --Region Control stuff
  230.  
  231. local DefaultRegions = {}
  232.  
  233. local searchLocations = {  game.Workspace.StaticStorage, game.Workspace.DynamicStorage, game.Workspace.CropStorage,
  234.                             game.Workspace.RockStorage,  game.Workspace.GrassStorage, --Optimizations should make this possible!
  235.                             game.Workspace.TreeStorage, game.Workspace.SaplingStorage }
  236.  
  237. function regionToString( region )
  238.     local finalString = ""
  239.     for o, v in pairs( region )do
  240.         for i, u in pairs( v )do
  241.             finalString = finalString .. math.floor(tonumber(u) + .5) .. ','
  242.         end
  243.         finalString = finalString .. ";"
  244.     end
  245.     return finalString
  246. end
  247.  
  248. function stringToRegion( regionString )
  249.     --print( regionString )
  250.     if( string.sub(regionString, 1, 1) == '[' )then --We have old data
  251.         return game:GetService("HttpService"):JSONDecode( regionString )
  252.     else
  253.         local finalRegion = { }
  254.         for i, v in pairs(splitString(regionString, ',;'))do
  255.             finalRegion[i] = {}
  256.             for o, u in pairs(splitString(v, ','))do  
  257.                 --print( i .. ":" .. o .. ":" .. u )
  258.                 finalRegion[i][o] = tonumber(u)
  259.             end
  260.         end
  261.         if( finalRegion[#finalRegion][1] == "" )then --So loading doesn't act funky
  262.             table.remove(finalRegion, #finalRegion)
  263.         end
  264.         return finalRegion
  265.     end
  266. end
  267.  
  268. function getRegionContents( BarnBase ) --Let's do some recursion and complex data stuff >:D JK Use my own functions :l
  269.     local lilX, lilZ = BarnBase.Position.X - 100, BarnBase.Position.Z - 75
  270.     local bigX, bigZ = BarnBase.Position.X + 100, BarnBase.Position.Z + 75
  271.     local foundObjects = { }
  272.     for _, l in pairs( searchLocations ) do
  273.         for __, t in pairs(l:getChildren())do
  274.             local part = t:findFirstChild("Base")
  275.              if( part and ( lilX < part.Position.X and part.Position.X < bigX )
  276.                  and ( lilZ < part.Position.Z and part.Position.Z < bigZ ) )then
  277.                 table.insert(foundObjects, t)  
  278.             end
  279.         end
  280.         end
  281.     return foundObjects
  282. end
  283.  
  284. local maxSize = 64998
  285.  
  286. function SaveRegion( Player, regionContents )
  287.     local savePieces = { regionContents }
  288.     --print( string.len(savePieces[#savePieces]))
  289.     while( string.len(savePieces[#savePieces]) > (maxSize - 10) )do
  290.         local piece = savePieces[#savePieces]  
  291.         savePieces[#savePieces] = string.sub(piece, 1, (maxSize - 10))
  292.         savePieces[#savePieces + 1] = string.sub(piece, (maxSize - 9))
  293.     end
  294.    
  295.     CurrentPlayerData[Player.userId][4] = {}
  296.    
  297.     local success, why = pcall(function()
  298.         for i, v in pairs( savePieces )do
  299.             --print( i )
  300.             RegionDataStore:SetAsync("REGION_" .. Player.userId .. "_" .. i, v)
  301.             CurrentPlayerData[Player.userId][4][i] = "REGION_" .. Player.userId .. "_" .. i
  302.         end
  303.     end)
  304.     print( ( success and "Barn Data Saved!" ) or why )
  305. end
  306.  
  307. function LoadRegion( Player )
  308.     local segments = CurrentPlayerData[Player.userId][4]
  309.     local region = ""
  310.    
  311.     local good = pcall( function()
  312.         for i, v in pairs(segments)do
  313.             region = region .. RegionDataStore:GetAsync( v )
  314.         end
  315.     end )
  316.     if( not good)then
  317.         print("BAD BAD BAD @LoadRegion")
  318.     end
  319.  
  320.     return region
  321. end
  322.  
  323. --JSON Functions
  324.  
  325. function ConvertRegionToJSON( regionContents, Barn )
  326.     if( Barn )then --We need the barn so we can correctly calculate the offset position of the objects
  327.         local BarnBPX = Barn.Base.Position.X
  328.         local BarnBPZ = Barn.Base.Position.Z
  329.         local finalTable = { }
  330.         if( tonumber( string.sub(Barn.Name, 5) ) < 4 )then--First three barns don't require rotation around the barn
  331.             for _, v in pairs(regionContents)do
  332.                 local o = { }
  333.                 o[1] = NameForIntegerIndex[v.Name]
  334.                 o[2] = v.Base.Position.X - BarnBPX
  335.                 o[3] = v.Base.Position.Z - BarnBPZ
  336.                 o[4] = ( math.abs(v.Base.Rotation.X) > 90 and 2 ) or math.floor(v.Base.Rotation.Y/90 + .5)
  337.                 if( v:findFirstChild("Age") )then
  338.                     o[5] = v.Age.Value
  339.                 end
  340.                 --o[6] = { } --No objects currently use this
  341.                 table.insert(finalTable, o)
  342.             end
  343.         else--Last three barns need roation applied to their positions
  344.             for _, v in pairs(regionContents)do
  345.                 local o = { }
  346.                 o[1] = NameForIntegerIndex[v.Name]
  347.                 o[2] = -1*( v.Base.Position.X - BarnBPX ) --Negate to rotate around barn
  348.                 o[3] = -1*( v.Base.Position.Z - BarnBPZ ) --Negate to rotate around barn
  349.                 o[4] = ( math.abs(v.Base.Rotation.X) > 90 and 2 + 2 ) or math.floor(v.Base.Rotation.Y/90 + .5)  + 2 --Add two to rotate 180 degrees
  350.                 if( v:findFirstChild("Age") )then
  351.                     o[5] = v.Age.Value
  352.                 end
  353.                 --o[6] = { } --No objects currently use this
  354.                 table.insert(finalTable, o)
  355.             end
  356.         end
  357.         --return game:GetService("HttpService"):JSONEncode(finalTable) --old
  358.         return regionToString( finalTable ) --new
  359.     end
  360. end
  361.  
  362. function addTag(where, who)
  363.     local tag = Instance.new("StringValue")
  364.     tag.Name = "Tag"
  365.     tag.Parent = where
  366.     tag.Value = ( who ~= nil and who ) or ""
  367. end
  368.  
  369. function DeployRegionFromJSON( JSONData, Barn, playerName )
  370.     --print( JSONData )
  371.     if( Barn )then --We need the barn so we can correctly calculate the offset position of the objects
  372.         --local regionTable = game:GetService("HttpService"):JSONDecode( JSONData ) --old
  373.         local regionTable = stringToRegion( JSONData ) --new
  374.         --print( #regionTable )
  375.         local BarnBPX = Barn.Base.Position.X
  376.         local BarnBPZ = Barn.Base.Position.Z   
  377.         if( tonumber( string.sub(Barn.Name, 5) ) < 4 )then--First three barns don't require rotation around the barn
  378.             for i, v in pairs( regionTable )do
  379.                 --print( v[1] )
  380.                 --print( IntegerForLocationIndex[ v[1] ] )
  381.                 if( i % 20 == 0 )then wait() end
  382.                 if( IntegerForLocationIndex[ v[1] ] )then --because I'm stupid
  383.                     if( IntegerForLocationIndex[ v[1] ] == game.Workspace.CropStorage )then --We have to do crops differantly
  384.                         local newName = IntegerForNameIndex[ v[1] ] --Makes the age proccess a bit easier
  385.                         local newObject = game.ServerStorage[ newName ]:clone()
  386.                         newObject.Parent = IntegerForLocationIndex[ v[1] ] or game.Workspace.StaticStorage
  387.                         newObject.Age.Value = v[5]
  388.                         --Complicated because crops move as they age
  389.                         local maxAge = CatalogModule.CropConfig[newName].Age
  390.                         if( v[5] < maxAge )then
  391.                             newObject.Base.CFrame = CFrame.new( v[2] + BarnBPX,
  392.                                  (v[5]/maxAge - .5)*newObject.Base.Size.Y + 1.2,
  393.                                  v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*v[4], 0)  
  394.                         elseif( v[5] == maxAge )then
  395.                             newObject.Base.CFrame = CFrame.new( v[2] + BarnBPX,
  396.                                  .5*newObject.Base.Size.Y + 1.2,
  397.                                  v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*v[4], 0)
  398.                             AdjustColor( newObject, BrickColor.new(CatalogModule.CropConfig[newName].Color) )
  399.                             if( CatalogModule.CropConfig[newName].Mature )then
  400.                                 AdjustMatureVis(newObject, true)
  401.                             end
  402.                         else --We know it is a dead crop x(
  403.                             newObject.Base.CFrame = CFrame.new( v[2] + BarnBPX,
  404.                                  ((maxAge-1)/maxAge - .5)*newObject.Base.Size.Y + 1.2,
  405.                                  v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*v[4], 0)
  406.                             AdjustColor( newObject, BrickColor.new(CatalogModule.CropConfig[newName].Death) )
  407.                             if( CatalogModule.CropConfig[newName].Mature )then
  408.                                 AdjustMatureVis(newObject, false)  
  409.                             end    
  410.                         end                  
  411.                         AdjustPosition( newObject, game.ServerStorage[ IntegerForNameIndex[ v[1] ] ] )
  412.                         local newPlot = game.ServerStorage.CropPlot:clone() --We have to make the crop base
  413.                         newPlot.Base.CFrame = CFrame.new(v[2] + BarnBPX, 1.3, v[3] + BarnBPZ)
  414.                         newPlot.Parent = newObject
  415.                         addTag(newObject, playerName)
  416.                     else
  417.                         local newObject = game.ServerStorage[ IntegerForNameIndex[ v[1] ] ]:clone()
  418.                         newObject.Parent = IntegerForLocationIndex[ v[1] ] or game.Workspace.StaticStorage
  419.                         newObject.Base.CFrame = CFrame.new( v[2] + BarnBPX, newObject.Base.Size.Y/2 + 1.2,
  420.                              v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*v[4], 0)
  421.                         AdjustPosition( newObject, game.ServerStorage[ IntegerForNameIndex[ v[1] ] ] )
  422.                         if( v[5] )then
  423.                             newObject.Age.Value = v[5]
  424.                         elseif( IntegerForLocationIndex[ v[1] ] == GW.StaticStorage or
  425.                                  IntegerForLocationIndex[ v[1] ] == GW.DynamicStorage )then
  426.                             addTag(newObject, playerName)
  427.                         end
  428.                     end
  429.                 end
  430.             end
  431.         else--Last three barns need roation applied to their positions
  432.             for i, v in pairs( regionTable )do
  433.                 if( i % 20 == 0 )then wait() end
  434.                 if( IntegerForLocationIndex[ v[1] ] )then --because I'm stupid
  435.                     if( IntegerForLocationIndex[ v[1] ] == game.Workspace.CropStorage )then --We have to do crops differantly
  436.                         local newName = IntegerForNameIndex[ v[1] ] --Makes the age proccess a bit easier
  437.                         local newObject = game.ServerStorage[ newName ]:clone()
  438.                         newObject.Parent = IntegerForLocationIndex[ v[1] ] or game.Workspace.StaticStorage
  439.                         newObject.Age.Value = v[5]
  440.                         --Complicated because crops move as they age
  441.                         local maxAge = CatalogModule.CropConfig[newName].Age
  442.                         if( v[5] < maxAge )then
  443.                             newObject.Base.CFrame = CFrame.new( -1*v[2] + BarnBPX,
  444.                                  (v[5]/maxAge - .5)*newObject.Base.Size.Y + 1.2,
  445.                                  -1*v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*( v[4] - 2 ), 0)  
  446.                         elseif( v[5] == maxAge )then
  447.                             newObject.Base.CFrame = CFrame.new( -1*v[2] + BarnBPX,
  448.                                  .5*newObject.Base.Size.Y + 1.2,
  449.                                  -1*v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*( v[4] - 2 ), 0)
  450.                             AdjustColor( newObject, BrickColor.new(CatalogModule.CropConfig[newName].Color) )
  451.                             if( CatalogModule.CropConfig[newName].Mature )then
  452.                                 AdjustMatureVis(newObject, true)
  453.                             end
  454.                         else --We know it is a dead crop x(
  455.                             newObject.Base.CFrame = CFrame.new( -1*v[2] + BarnBPX,
  456.                                  ((maxAge-1)/maxAge - .5)*newObject.Base.Size.Y + 1.2,
  457.                                  -1*v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*( v[4] - 2 ), 0)
  458.                             AdjustColor( newObject, BrickColor.new(CatalogModule.CropConfig[newName].Death) )
  459.                             if( CatalogModule.CropConfig[newName].Mature )then
  460.                                 AdjustMatureVis(newObject, false)  
  461.                             end    
  462.                         end                  
  463.                         AdjustPosition( newObject, game.ServerStorage[ IntegerForNameIndex[ v[1] ] ] )
  464.                         local newPlot = game.ServerStorage.CropPlot:clone() --We have to make the crop base
  465.                         newPlot.Base.CFrame = CFrame.new(-1*v[2] + BarnBPX, 1.3, -1*v[3] + BarnBPZ)
  466.                         newPlot.Parent = newObject
  467.                         addTag(newObject, playerName)
  468.                     else
  469.                         local newObject = game.ServerStorage[ IntegerForNameIndex[ v[1] ] ]:clone()
  470.                         newObject.Parent = IntegerForLocationIndex[ v[1] ] or game.Workspace.StaticStorage
  471.                         newObject.Base.CFrame = CFrame.new( -1*v[2] + BarnBPX, newObject.Base.Size.Y/2 + 1.2,
  472.                              -1*v[3] + BarnBPZ ) * CFrame.Angles(0, (math.pi/2)*( v[4] - 2 ), 0)
  473.                         AdjustPosition( newObject, game.ServerStorage[ IntegerForNameIndex[ v[1] ] ] )
  474.                         if( v[5] )then
  475.                             newObject.Age.Value = v[5]
  476.                         elseif( IntegerForLocationIndex[ v[1] ] == GW.StaticStorage or
  477.                                  IntegerForLocationIndex[ v[1] ] == GW.DynamicStorage )then
  478.                             addTag(newObject, playerName)
  479.                         end
  480.                     end
  481.                 end
  482.             end
  483.         end
  484.     end
  485. end
  486.  
  487. --Model Manipulation
  488.  
  489. function AdjustModelPos( Model, Template, InternalName )
  490.     for i, v in pairs(Model[InternalName]:GetChildren()) do
  491.         if( v:IsA("BasePart") )then
  492.             v.CFrame = Model.Base.CFrame:toWorldSpace(Template.Base.CFrame:toObjectSpace(Template[InternalName][v.Name].CFrame))
  493.         end
  494.     end
  495. end
  496.  
  497. function AdjustPosition(Model, Template, InternalName) --Root Part Called Base
  498.     for i, v in pairs(Model:GetChildren()) do
  499.         if( v.Name ~= "Base" and ( v:IsA("BasePart") or v:IsA("UnionOperation") ) )then
  500.             v.CFrame = Model.Base.CFrame:toWorldSpace(Template.Base.CFrame:toObjectSpace(Template[v.Name].CFrame))
  501.         elseif( v:IsA("Model") )then
  502.             AdjustModelPos( Model, Template, v.Name )  
  503.         end
  504.     end
  505. end
  506.  
  507. --Plant Stuff
  508.  
  509. function AdjustColor(Model, Color)
  510.     for i, v in pairs(Model:getChildren()) do
  511.         if( v:IsA("Part") or v:IsA("UnionOperation") )then
  512.             v.BrickColor = Color
  513.         --elseif( v:IsA("Model") and v.Name ~= "CropPlot" )then --Mature does it itself
  514.         --  AdjustColor(v, Color)
  515.         end
  516.     end
  517. end
  518.  
  519. function AdjustMatureVis(Model, Visible)
  520.     local Trans = ( Visible and 0 ) or 1
  521.     for _, v in pairs(Model.Mature:getChildren())do
  522.         if( v:IsA("Part") )then
  523.             v.Transparency = Trans
  524.         end
  525.     end
  526. end
  527.  
  528. --Actual code for when does happen stuff
  529.  
  530. local safe = true --Set to false after loading is complete!
  531. BarnSetupFunction = Instance.new("RemoteFunction")
  532. BarnSetupFunction.Name = "SetupBarn" --We messed up the naming :'(
  533. BarnSetupFunction.OnServerInvoke = function( Player )
  534.     while( safe )do wait(1) end
  535.     safe = true
  536.    
  537.     local Barn = nil
  538.     for i, v in pairs(game.Workspace.BarnStorage:GetChildren())do
  539.         if( not v:findFirstChild("Owner") )then
  540.             Barn = v
  541.             break
  542.         end
  543.     end
  544.     if( not Barn or Player.Barn.Value ~= nil and Player.Parent ~= nil )then safe = false; return false; end --One last check
  545.    
  546.     Player.Barn.Value = Barn
  547.                
  548.     local Owner = Instance.new("StringValue") --Do this first to avoid other people stealing your barn
  549.     Owner.Name = "Owner"
  550.     Owner.Parent = Barn            
  551.                    
  552.     local good = pcall( function()
  553.         local playerData = CurrentPlayerData[ Player.userId ]
  554.         if( playerData[4][1] == nil )then --Client doesn't have anything to load
  555.             local region = ConvertRegionToJSON( getRegionContents( Barn.Base ), Barn )
  556.             SaveRegion( Player, region )
  557.             --RegionDataStore:SetAsync( "REGION_" .. Player.userId .. "_1", ConvertRegionToJSON( region, Barn ) )
  558.             --1playerData[4][1] = "REGION_" .. Player.userId .. "_1"
  559.         else --They are loading a past region
  560.             local region = getRegionContents( Barn.Base )
  561.             for _, v in pairs(region)do
  562.                 v:Destroy()
  563.             end
  564.             --print( playerData[4][1] )
  565.             --print( RegionDataStore:GetAsync( playerData[4][1] ) )
  566.             --DeployRegionFromJSON( RegionDataStore:GetAsync( playerData[4][1] ), Barn, Player.Name )
  567.             DeployRegionFromJSON( LoadRegion( Player ), Barn, Player.Name )
  568.         end
  569.        
  570.         for _, v in pairs(playerData[2])do --Load the people able to use the barn
  571.             local newPlayer = Instance.new("StringValue", Barn.Control.Players)    
  572.             newPlayer.Name = string.lower(v) --Makes the names not case sensitive. See the barn control script
  573.             newPlayer.Value = v
  574.         end
  575.        
  576.         if( not Barn.Control.Players:findFirstChild( string.lower(Player.Name) ) )then--We want the owner to be able to use the barn!
  577.             local newPlayer = Instance.new("StringValue", Barn.Control.Players)    
  578.             newPlayer.Name = string.lower(Player.Name) --Makes the names not case sensitive. See the barn control script
  579.             newPlayer.Value = Player.Name
  580.         end
  581.        
  582.         for k, v in pairs(playerData[3])do --Load the resources saved in the barn
  583.             if( Barn.Control.Resources:findFirstChild(k) )then --Resources come and go; we don't wanna break anything
  584.                 Barn.Control.Resources[k].Value = v
  585.             end
  586.         end
  587.    
  588.         Owner.Value = Player.Name --Do this last to avoid autosave unleashing evil
  589.     end)
  590.    
  591.     if( not good )then
  592.         print("ERROR SETTING UP BARN")
  593.         Player.Barn.Value = nil
  594.         Owner:destroy()    
  595.         safe = false
  596.         return false
  597.     else
  598.         safe = false
  599.         return true
  600.     end
  601.    
  602.     --safe = false
  603.     --return true --Everything Worked! 
  604. end
  605. BarnSetupFunction.Parent = game.ReplicatedStorage
  606.  
  607.  
  608. game.Players.PlayerAdded:connect( function( newPlayer )
  609.     local good = pcall( function() --We have to load the player data so we can do stuff with it later
  610.         local currentData = loadPlayerData( newPlayer )
  611.         currentData[1] = newPlayer.Name
  612.         CurrentPlayerData[ newPlayer.userId ] = currentData
  613.     end)
  614.     if( not good ) then newPlayer:Kick("Data Loading Issue, Please Try Again") end
  615. end)
  616.  
  617.  
  618. game.Players.PlayerRemoving:connect( function( oldPlayer ) pcall( function() --We have to save everything and stuff
  619.     if( oldPlayer:findFirstChild("Barn") and oldPlayer.Barn.Value ~= nil )then
  620.         local Barn = oldPlayer.Barn.Value
  621.        
  622.         Barn:WaitForChild("Owner")
  623.         while( Barn:findFirstChild("Owner") and Barn.Owner.Value == "" )do wait() end
  624.        
  625.         while( safe )do wait(1) end
  626.         safe = true
  627.        
  628.         if( Barn:findFirstChild("Owner") and Barn.Owner.Value == oldPlayer.Name )then --Make sure a player owns the barn
  629.             pcall( function()
  630.                 local PlayerData = CurrentPlayerData[ oldPlayer.userId ]
  631.                 if( PlayerData )then --We found where to save the region!
  632.                     Barn.Owner.Value = "" --Prevent evil autosave stuff
  633.                     local region = getRegionContents( Barn.Base )
  634.                     SaveRegion( oldPlayer, ConvertRegionToJSON(region, Barn) )
  635.                     updatePlayerData( oldPlayer, Barn )
  636.                     --Refresh Barn
  637.                     for _, v in pairs( Barn.Control.Players:getChildren() )do
  638.                         v:Destroy()
  639.                     end            
  640.                     for _, v in pairs( Barn.Control.Resources:getChildren() )do
  641.                         v.Value = 0
  642.                     end            
  643.                     Barn.Owner:Destroy()
  644.                     --Now restore the region
  645.                     for _,v in pairs(region)do
  646.                         v:Destroy()
  647.                     end
  648.                     DeployRegionFromJSON( DefaultRegions[tonumber( string.sub(Barn.Name, 5) )], Barn )
  649.                 end
  650.             end)
  651.         end
  652.        
  653.         safe = false
  654.     end
  655. end) end)
  656.  
  657.  
  658. game.OnClose = function()  --We got to save the stuffs
  659.     for _, Barn in pairs(game.Workspace.BarnStorage:GetChildren())do
  660.         if( Barn:findFirstChild("Owner") and game.Players:FindFirstChild(Barn.Owner.Value) )then --Make sure a player owns the barn
  661.             local Player =  game.Players:FindFirstChild(Barn.Owner.Value)              
  662.             local playerData = CurrentPlayerData[ Player.userId ]
  663.             if( playerData and playerData[4][1] )then --We found where to save the region!
  664.                 local region = getRegionContents( Barn.Base )
  665.                 SaveRegion( Player, ConvertRegionToJSON(region, Barn) )
  666.                 --pcall( function()
  667.                 --  RegionDataStore:SetAsync( playerData[4][1], ConvertRegionToJSON( region, Barn ) )
  668.                 --end )
  669.                 updatePlayerData( Player, Barn )
  670.             end
  671.         end    
  672.     end
  673. end
  674.  
  675. game.ReplicatedStorage:WaitForChild("ResetFarmCommand").OnServerEvent:connect(function(Player, confirm, p)
  676.     if( confirm and Player and Player == p and Player:findFirstChild("Barn") and Player.Barn.Value )then --safety first
  677.         local Barn = Player.Barn.Value
  678.         if( Barn:findFirstChild("Owner") and Barn.Owner.Value == Player.Name )then --Make sure a player owns the barn
  679.             local region = getRegionContents( Barn.Base )
  680.             for _,v in pairs(region)do
  681.                 v:Destroy()
  682.             end
  683.             DeployRegionFromJSON( DefaultRegions[tonumber( string.sub(Barn.Name, 5) )], Barn )
  684.         end
  685.     end
  686. end)
  687.  
  688.  
  689. script.Parent.DecorDeployed.Event:connect( function() --Everything that runs after the game is ready
  690.     --wait(1)
  691.     for _, v in pairs(game.Workspace.BarnStorage:GetChildren())do
  692.         local region = getRegionContents( v.Base )
  693.         --print( #region )
  694.         --print( tonumber( string.sub(v.Name, 5) ) )
  695.         DefaultRegions[ tonumber( string.sub(v.Name, 5) ) ] = ConvertRegionToJSON( region, v )  --old, but okay because we lie about JSON
  696.         --for _, o in pairs(region)do --For Testing
  697.         --  o:Destroy()
  698.         --end
  699.     end
  700.    
  701.     --wait(1)
  702.    
  703.     --for _, v in pairs(game.Workspace.BarnStorage:GetChildren())do --Second half of the testing
  704.         --print( DefaultRegions[tonumber( string.sub(v.Name, 5) )] )
  705.         --DeployRegionFromJSON( DefaultRegions[ tonumber( string.sub(v.Name, 5) ) ], v )
  706.     --end
  707.    
  708.     safe = false --I know opposite of what it means
  709.    
  710.     while wait(1) do --Using other wait
  711.         print("AUTOSAVE")
  712.         for _, Barn in pairs(game.Workspace.BarnStorage:GetChildren())do
  713.             while( safe )do wait(1) end
  714.             safe = true
  715.             if( Barn:findFirstChild("Owner") )then --Make sure a player owns the barn
  716.                 if( game.Players:FindFirstChild(Barn.Owner.Value) )then
  717.                     local Player =  game.Players:FindFirstChild(Barn.Owner.Value)              
  718.                     local playerData = CurrentPlayerData[ Player.userId ]
  719.                     if( playerData and playerData[4][1] )then --We found where to save the region!
  720.                         local region = ConvertRegionToJSON( getRegionContents( Barn.Base ), Barn )
  721.                         SaveRegion( Player, region )
  722.                         --RegionDataStore:SetAsync( playerData[4][1], ConvertRegionToJSON( region, Barn ) )
  723.                         updatePlayerData( Player, Barn )
  724.                     end
  725.                 else                   
  726.                     --wait(5)
  727.                     local good = pcall( function()
  728.                         if( Barn:findFirstChild("Owner") and Barn.Owner.Value ~= "" and not game.Players:FindFirstChild(Barn.Owner.Value) )then
  729.                             print("Broken Barn Found")
  730.                             local region = getRegionContents( Barn.Base )
  731.                             for _, o in pairs(region)do --For Testing
  732.                                 o:Destroy()
  733.                             end
  734.                             DeployRegionFromJSON( DefaultRegions[tonumber( string.sub(Barn.Name, 5) )], Barn )
  735.                             for _, v in pairs( Barn.Control.Players:getChildren() )do
  736.                                 v:Destroy()
  737.                             end            
  738.                             for _, v in pairs( Barn.Control.Resources:getChildren() )do
  739.                                 v.Value = 0
  740.                             end
  741.                             Barn.Owner:Destroy()
  742.                         end
  743.                     end )
  744.                     if( not good )then
  745.                         print("ERROR REMOVING BROKEN BARN")
  746.                     end
  747.                 end
  748.             end    
  749.             safe = false
  750.             wait(30) --Slows down saving
  751.         end
  752.     end
  753. end )
Add Comment
Please, Sign In to add comment