W0rMz000

Minecraft Seed Cracker/Finder

Jan 31st, 2020
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 32.13 KB | None | 0 0
  1. import argparse
  2. import itertools
  3. import numpy
  4. import pyopencl
  5. import sys
  6. import time
  7.  
  8.  
  9. def javaInt32(val):
  10.     return ((val + (1 << 31)) % (1 << 32)) - (1 << 31)
  11. #javaInt32()
  12.  
  13.  
  14. def javaInt64(val):
  15.     return ((val + (1 << 63)) % (1 << 64)) - (1 << 63)
  16. #javaInt64()
  17.  
  18.  
  19. def javaRandomInts(seed, size, count=1):
  20.     seed = javaInt64(seed ^ 0x5DEECE66D) & ((1 << 48) - 1)
  21.     vals = list()
  22.     while len(vals) < count:
  23.         bits = 0
  24.         vals.append(size)
  25.         while javaInt32(bits - vals[-1] + size - 1) < 0:
  26.             seed = javaInt64(seed * 0x5DEECE66D + 0xB) & ((1 << 48) - 1)
  27.             bits = javaInt32(seed >> (48 - 31)) & ((1 << 31) - 1)
  28.             vals[-1] = bits % size
  29.     return vals
  30. #javaRandomInts()
  31.  
  32.  
  33. def javaRandomLongs(seed, count=1):
  34.     seed = javaInt64(seed ^ 0x5DEECE66D) & ((1 << 48) - 1)
  35.     vals = list()
  36.     while len(vals) < count:
  37.         seed = javaInt64(seed * 0x5DEECE66D + 0xB) & ((1 << 48) - 1)
  38.         vals.append(javaInt32((seed >> (48 - 32)) & ((1 << (64 - 48 + 32)) - 1)) << 32)
  39.         seed = javaInt64(seed * 0x5DEECE66D + 0xB) & ((1 << 48) - 1)
  40.         vals[-1] = javaInt64(vals[-1] + javaInt32((seed >> (48 - 32)) & ((1 << (64 - 48 + 32)) - 1)))
  41.     return vals
  42. #javaRandomLongs()
  43.  
  44.  
  45. def getSlimeChunkHash(worldseed, cx, cz): # alpha
  46.     return javaInt64(worldseed + javaInt32(cx*cx*4987142) + javaInt32(cx*5947611) + javaInt64(cz*cz*4392871) + javaInt32(cz*389711))
  47. #getSlimeChunkHash()
  48.  
  49.  
  50. def isSlimeChunkOK(hash, cx, cz, magic=987234911): # alpha
  51.     return (javaRandomInts(javaInt64(hash ^ magic), 10)[0] == 0)
  52. #isSlimeChunkOK()
  53.  
  54.  
  55. def getVillageChunkHash(worldseed, cx, cz, magic=10387312): # beta
  56.     return javaInt64(worldseed + cx//32*341873128712 + cz//32*132897987541 + magic)
  57. #getVillageChunkHash()
  58.  
  59.  
  60. def isVillageChunkOK(hash, cx, cz): # beta
  61.     vals = javaRandomInts(hash, 24, 2)
  62.     return ((vals[0] == (cx % 32)) and (vals[1] == (cz % 32)))
  63. #isVillageChunkOK()
  64.  
  65.  
  66. def getFeatureChunkHash(worldseed, cx, cz, magic=14357617): # 1.3.1 (Desert/Jungle Temple), 1.4.2 (Witch Hut), 1.9 (Igloo)
  67.     return javaInt64(worldseed + cx//32*341873128712 + cz//32*132897987541 + magic)
  68. #getFeatureChunkHash()
  69.  
  70.  
  71. def isFeatureChunkOK(hash, cx, cz): # 1.3.1 (Desert/Jungle Temple), 1.4.2 (Witch Hut), 1.9 (Igloo)
  72.     vals = javaRandomInts(hash, 24, 2)
  73.     return ((vals[0] == (cx % 32)) and (vals[1] == (cz % 32)))
  74. #isFeatureChunkOK()
  75.  
  76.  
  77. def getMonumentChunkHash(worldseed, cx, cz, magic=10387313): # 1.8
  78.     return javaInt64(worldseed + cx//32*341873128712 + cz//32*132897987541 + magic)
  79. #getMonumentChunkHash()
  80.  
  81.  
  82. def isMonumentChunkOK(hash, cx, cz): # 1.8
  83.     vals = javaRandomInts(hash, 27, 4)
  84.     return ((int(float(vals[0] + vals[1]) / 2.0) == (cx % 32)) and (int(float(vals[2] + vals[3]) / 2.0) == (cz % 32)))
  85.     # must also have DeepOcean at center, and [Deep|Frozen]<Ocean|River> in radius 29 from center
  86. #isMonumentChunkOK()
  87.  
  88.  
  89. def getEndCityChunkHash(worldseed, cx, cz, magic=10387313): # 1.9
  90.     return javaInt64(worldseed + cx//20*341873128712 + cz//20*132897987541 + magic)
  91. #getEndCityChunkHash()
  92.  
  93.  
  94. def isEndCityChunkOK(hash, cx, cz): # 1.9
  95.     vals = javaRandomInts(hash, 9, 4)
  96.     return ((int(float(vals[0] + vals[1]) / 2.0) == (cx % 20)) and (int(float(vals[2] + vals[3]) / 2.0) == (cz % 20)))
  97.     # must also have Island height 60+
  98. #isEndCityChunkOK()
  99.  
  100.  
  101. def getMansionChunkHash(worldseed, cx, cz, magic=10387319): # 1.11
  102.     return javaInt64(worldseed + cx//80*341873128712 + cz//80*132897987541 + magic)
  103. #getMansionChunkHash()
  104.  
  105.  
  106. def isMansionChunkOK(hash, cx, cz): # 1.11
  107.     vals = javaRandomInts(hash, 60, 4)
  108.     return ((int(float(vals[0] + vals[1]) / 2.0) == (cx % 80)) and (int(float(vals[2] + vals[3]) / 2.0) == (cz % 80)))
  109. #isMansionChunkOK()
  110.  
  111.  
  112. def parseArgumentChunks(chunklist, blocklist):
  113.     chunks = set()
  114.     for chunk in chunklist:
  115.         cx,cz = chunk.split(',')
  116.         chunks.add( (int(cx),int(cz)) )
  117.     for block in blocklist:
  118.         bx,bz = block.split(',')
  119.         chunks.add( (int(bx)//16,int(bz)//16) )
  120.     return chunks
  121. #parseArgumentChunks()
  122.  
  123.  
  124. def timeToString(s):
  125.     s,u = int(s),int(s*100)%100
  126.     m,s = s//60,s%60
  127.     h,m = m//60,m%60
  128.     d,h = h//24,h%24
  129.     str = ""
  130.     if d:
  131.         str += "%dd" % d
  132.     if d or h:
  133.         str += "%dh" % h
  134.     if d or h or m:
  135.         str += "%dm" % m
  136.     str += "%d" % s
  137.     if (not (d or h or m)) and (s < 10):
  138.         str += ".%02d" % u
  139.     str += "s"
  140.     return str
  141. #timeToString()
  142.  
  143.  
  144. if __name__ == "__main__":
  145.     # define usage and parse arguments
  146.     parser = argparse.ArgumentParser(description="Seed Cracker")
  147.     parser.add_argument('--version', action='version', version='1.0')
  148.     parser.add_argument('--list-devices', action='store_true',
  149.             help="list the OpenCL devices available on your computer"
  150.     )
  151.     parser.add_argument('--devices', type=int, metavar='index', nargs='+', action='append', default=[],
  152.             help="the particular OpenCL device(s) to use for seed scanning, identified by their index from --list-devices (default: automatic)"
  153.     )
  154.     parser.add_argument('-w', '--world-seed', type=int, metavar='seed', nargs='+', action='append', default=[],
  155.             help="world seed(s) for which to validate other provided feature locations"
  156.     )
  157.     parser.add_argument('--ss', '--seed-slime', type=int, metavar='seed', nargs='?', default=10387313, const=None,
  158.             help="the custom Spigot seed-slime, or leave blank to derive it with the world seed and slime chunk locations"
  159.     )
  160.     parser.add_argument('--sv', '--seed-village', type=int, metavar='seed', nargs='?', default=10387312, const=None,
  161.             help="the custom Spigot seed-village, or leave blank to derive it with the world seed and village locations"
  162.     )
  163.     parser.add_argument('--sf', '--seed-feature', type=int, metavar='seed', nargs='?', default=14357617, const=None,
  164.             help="the custom Spigot seed-feature, or leave blank to derive it with the world seed and scattered feature locations"
  165.     )
  166.     parser.add_argument('--sm', '--seed-monument', type=int, metavar='seed', nargs='?', default=10387313, const=None,
  167.             help="the custom Spigot seed-monument, or leave blank to derive it with the world seed and monument locations"
  168.     )
  169.     parser.add_argument('--se', '--seed-endcity', type=int, metavar='seed', nargs='?', default=10387313, const=None,
  170.             help="the custom Spigot seed-endcity, or leave blank to derive it with the world seed and end city locations"
  171.     )
  172.     parser.add_argument('-s', '--sc', '--slime-chunk', type=str, metavar='cx,cz', nargs='+', action='append', default=[],
  173.             help="comma-separated chunk coordinate(s) of slime spawning chunks",
  174.     )
  175.     parser.add_argument('-S', '--sb', '--slime-block', type=str, metavar='bx,bz', nargs='+', action='append', default=[],
  176.             help="comma-separated block coordinate(s) of slime spawning chunks",
  177.     )
  178.     parser.add_argument('-v', '--vc', '--village-chunk', type=str, metavar='cx,cz', nargs='+', action='append', default=[],
  179.             help="comma-separated chunk coordinate(s) of village wells",
  180.     )
  181.     parser.add_argument('-V', '--vb', '--village-block', type=str, metavar='bx,bz', nargs='+', action='append', default=[],
  182.             help="comma-separated block coordinate(s) of village wells",
  183.     )
  184.     parser.add_argument('-f', '--fc', '--feature-chunk', type=str, metavar='cx,cz', nargs='+', action='append', default=[],
  185.             help="comma-separated chunk coordinate(s) of scattered features (witch huts, desert/jungle temples, igloos)",
  186.     )
  187.     parser.add_argument('-F', '--fb', '--feature-block', type=str, metavar='bx,bz', nargs='+', action='append', default=[],
  188.             help="comma-separated block coordinate(s) of scattered features (witch huts, desert/jungle temples, igloos)",
  189.     )
  190.     parser.add_argument('-m', '--mc', '--monument-chunk', type=str, metavar='cx,cz', nargs='+', action='append', default=[],
  191.             help="comma-separated chunk coordinate(s) of ocean monuments",
  192.     )
  193.     parser.add_argument('-M', '--mb', '--monument-block', type=str, metavar='bx,bz', nargs='+', action='append', default=[],
  194.             help="comma-separated block coordinate(s) of ocean monuments",
  195.     )
  196.     parser.add_argument('-e', '--ec', '--endcity-chunk', type=str, metavar='cx,cz', nargs='+', action='append', default=[],
  197.             help="comma-separated chunk coordinate(s) of end cities",
  198.     )
  199.     parser.add_argument('-E', '--eb', '--endcity-block', type=str, metavar='bx,bz', nargs='+', action='append', default=[],
  200.             help="comma-separated block coordinate(s) of end cities",
  201.     )
  202.     parser.add_argument('-a', '--ac', '--mansion-chunk', type=str, metavar='cx,cz', nargs='+', action='append', default=[],
  203.             help="comma-separated chunk coordinate(s) of woodland mansions",
  204.     )
  205.     parser.add_argument('-A', '--ab', '--mansion-block', type=str, metavar='bx,bz', nargs='+', action='append', default=[],
  206.             help="comma-separated block coordinate(s) of woodland mansions",
  207.     )
  208.     parser.add_argument('-r', '--resume', type=int, metavar='n', default=0,
  209.             help="spot to resume a seed search that was stopped with Ctrl-C",
  210.     )
  211.     if len(sys.argv) <= 1:
  212.         parser.print_usage()
  213.         print("-h for more information")
  214.         sys.exit(2)
  215.     args = parser.parse_args()
  216.     worldseeds = sorted(set(itertools.chain(*args.world_seed)))
  217.     slimechunks = parseArgumentChunks(itertools.chain(*args.sc), itertools.chain(*args.sb))
  218.     villagechunks = parseArgumentChunks(itertools.chain(*args.vc), itertools.chain(*args.vb))
  219.     featurechunks = parseArgumentChunks(itertools.chain(*args.fc), itertools.chain(*args.fb))
  220.     monumentchunks = parseArgumentChunks(itertools.chain(*args.mc), itertools.chain(*args.mb))
  221.     endcitychunks = parseArgumentChunks(itertools.chain(*args.ec), itertools.chain(*args.eb))
  222.     mansionchunks = parseArgumentChunks(itertools.chain(*args.ac), itertools.chain(*args.ab))
  223.    
  224.     # list OpenCL devices?
  225.     if args.list_devices:
  226.         d = 0
  227.         print("Listing available OpenCL devices ...")
  228.         for platform in pyopencl.get_platforms():
  229.             for device in platform.get_devices():
  230.                 d += 1
  231.                 print("  #%d: %s on %s (%s)" % (d, platform.name, device.name, platform.version))
  232.         print("... OK: %d devices" % (d,))
  233.         sys.exit(0)
  234.     #if list_devices
  235.    
  236.     # validate provided seeds?
  237.     if len(worldseeds) > 0 and args.sv != None and args.sf != None and args.sm != None and args.ss != None:
  238.         print("Validating provided world seeds and locations using Python logic ...")
  239.         for s in worldseeds:
  240.             out = ""
  241.             if slimechunks:
  242.                 sNum = 0
  243.                 for cx,cz in slimechunks:
  244.                     if isSlimeChunkOK(getSlimeChunkHash(s, cx, cz), cx, cz, args.ss):
  245.                         sNum += 1
  246.                 out += "%s%d/%d slime chunks" % ((", " if out else ""),sNum,len(slimechunks))
  247.             if villagechunks:
  248.                 vNum = 0
  249.                 for cx,cz in villagechunks:
  250.                     if isVillageChunkOK(getVillageChunkHash(s, cx, cz, args.sv), cx, cz):
  251.                         vNum += 1
  252.                 out += "%s%d/%d villages" % ((", " if out else ""),vNum,len(villagechunks))
  253.             if featurechunks:
  254.                 fNum = 0
  255.                 for cx,cz in featurechunks:
  256.                     if isFeatureChunkOK(getFeatureChunkHash(s, cx, cz, args.sf), cx, cz):
  257.                         fNum += 1
  258.                 out += "%s%d/%d features" % ((", " if out else ""),fNum,len(featurechunks))
  259.             if monumentchunks:
  260.                 mNum = 0
  261.                 for cx,cz in monumentchunks:
  262.                     if isMonumentChunkOK(getMonumentChunkHash(s, cx, cz, args.sm), cx, cz):
  263.                         mNum += 1
  264.                 out += "%s%d/%d monuments" % ((", " if out else ""),mNum,len(monumentchunks))
  265.             if endcitychunks:
  266.                 fNum = 0
  267.                 for cx,cz in endcitychunks:
  268.                     if isEndCityChunkOK(getEndCityChunkHash(s, cx, cz, args.sm), cx, cz):
  269.                         fNum += 1
  270.                 out += "%s%d/%d end cities" % ((", " if out else ""),fNum,len(endcitychunks))
  271.             if mansionchunks:
  272.                 mNum = 0
  273.                 for cx,cz in mansionchunks:
  274.                     if isMansionChunkOK(getMansionChunkHash(s, cx, cz), cx, cz):
  275.                         mNum += 1
  276.                 out += "%s%d/%d mansions" % ((", " if out else ""),mNum,len(mansionchunks))
  277.             print("  %d matches %s" % (s,out))
  278.         print("... OK")
  279.     #if worldseeds
  280.    
  281.     # dynamically generate an OpenCL kernel function
  282.     kernel = """
  283. __kernel void test_seeds(
  284.     const long seedbase,
  285.     const char asTimestamp,
  286.     __global volatile long *hits,
  287.     __global volatile uint *count
  288. ) {
  289.     long seed = seedbase + get_global_id(0);
  290.     long rand;
  291.     int bits, val, val2;
  292.    
  293.     /* DISABLED timestamp-derived scan; newer JDK uses System.nanoTime() and a secondary Uniquifier() which depends how many instances of Random() have ever been created
  294.     if (asTimestamp != 0) {
  295.         rand = (seed ^ 0x5deece66dL) & ((1L << 48) - 1);
  296.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  297.         seed = (long)( (int)( (rand >> (48 - 32)) & ((1L << (64 - 48 + 32)) - 1) ) ) << 32;
  298.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  299.         seed = seed + (int)( (rand >> (48 - 32)) & ((1L << (64 - 48 + 32)) - 1) );
  300.     }
  301.     */
  302.    
  303. """ + "\n".join(("""
  304.     rand = ((seed + %dL) ^ 0x5deece66dL) & ((1L << 48) - 1);
  305.     do {
  306.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  307.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  308.         val = bits %% 24;
  309.     } while (bits - val + (24 - 1) < 0);
  310.     if (val != %d)
  311.         return;
  312.     do {
  313.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  314.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  315.         val = bits %% 24;
  316.     } while (bits - val + (24 - 1) < 0);
  317.     if (val != %d)
  318.         return;
  319. """ % (getVillageChunkHash(0,cx,cz,args.sv),cx%32,cz%32)) for cx,cz in villagechunks if (args.sv != None)) + """
  320.    
  321. """ + "\n".join(("""
  322.     rand = ((seed + %dL) ^ 0x5deece66dL) & ((1L << 48) - 1);
  323.     do {
  324.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  325.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  326.         val = bits %% 24;
  327.     } while (bits - val + (24 - 1) < 0);
  328.     if (val != %d)
  329.         return;
  330.     do {
  331.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  332.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  333.         val = bits %% 24;
  334.     } while (bits - val + (24 - 1) < 0);
  335.     if (val != %d)
  336.         return;
  337. """ % (getFeatureChunkHash(0,cx,cz,args.sf),cx%32,cz%32)) for cx,cz in featurechunks if (args.sf != None)) + """
  338.    
  339. """ + "\n".join(("""
  340.     rand = ((seed + %dL) ^ 0x5deece66dL) & ((1L << 48) - 1);
  341.     do {
  342.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  343.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  344.         val = bits %% 27;
  345.     } while (bits - val + (27 - 1) < 0);
  346.     do {
  347.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  348.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  349.         val2 = bits %% 27;
  350.     } while (bits - val2 + (27 - 1) < 0);
  351.     if ((val + val2) / 2 != %d)
  352.         return;
  353.     do {
  354.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  355.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  356.         val = bits %% 27;
  357.     } while (bits - val + (27 - 1) < 0);
  358.     do {
  359.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  360.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  361.         val2 = bits %% 27;
  362.     } while (bits - val2 + (27 - 1) < 0);
  363.     if ((val + val2) / 2 != %d)
  364.         return;
  365. """ % (getMonumentChunkHash(0,cx,cz,args.sm),cx%32,cz%32)) for cx,cz in monumentchunks if (args.sm != None)) + """
  366.    
  367. """ + "\n".join(("""
  368.     rand = ((seed + %dL) ^ 0x5deece66dL) & ((1L << 48) - 1);
  369.     do {
  370.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  371.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  372.         val = bits %% 9;
  373.     } while (bits - val + (9 - 1) < 0);
  374.     do {
  375.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  376.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  377.         val2 = bits %% 9;
  378.     } while (bits - val2 + (9 - 1) < 0);
  379.     if ((val + val2) / 2 != %d)
  380.         return;
  381.     do {
  382.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  383.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  384.         val = bits %% 9;
  385.     } while (bits - val + (9 - 1) < 0);
  386.     do {
  387.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  388.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  389.         val2 = bits %% 9;
  390.     } while (bits - val2 + (9 - 1) < 0);
  391.     if ((val + val2) / 2 != %d)
  392.         return;
  393. """ % (getEndCityChunkHash(0,cx,cz),cx%20,cz%20)) for cx,cz in endcitychunks) + """
  394.    
  395. """ + "\n".join(("""
  396.     rand = ((seed + %dL) ^ 0x5deece66dL) & ((1L << 48) - 1);
  397.     do {
  398.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  399.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  400.         val = bits %% 60;
  401.     } while (bits - val + (60 - 1) < 0);
  402.     do {
  403.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  404.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  405.         val2 = bits %% 60;
  406.     } while (bits - val2 + (60 - 1) < 0);
  407.     if ((val + val2) / 2 != %d)
  408.         return;
  409.     do {
  410.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  411.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  412.         val = bits %% 60;
  413.     } while (bits - val + (60 - 1) < 0);
  414.     do {
  415.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  416.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  417.         val2 = bits %% 60;
  418.     } while (bits - val2 + (60 - 1) < 0);
  419.     if ((val + val2) / 2 != %d)
  420.         return;
  421. """ % (getMansionChunkHash(0,cx,cz),cx%80,cz%80)) for cx,cz in mansionchunks) + """
  422.    
  423. """ + "\n".join(("""
  424.     rand = ((seed + %dL) ^ %dL ^ 0x5deece66dL) & ((1L << 48) - 1);
  425.     do {
  426.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  427.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  428.         val = bits %% 10;
  429.     } while (bits - val + (10 - 1) < 0);
  430.     if (val != 0)
  431.         return;
  432. """ % (getSlimeChunkHash(0,cx,cz),args.ss)) for cx,cz in slimechunks if (args.ss != None)) + """
  433.    
  434.     val = (int) atomic_inc(count);
  435.     if ((val >= 0 && val < 16)) {
  436.         hits[val] = seed;
  437.     } else {
  438.         atomic_xchg(count, 16);
  439.     }
  440. }
  441. """
  442.    
  443.     # add kernel functions for slime/village/feature/monument seed search, if possible
  444.     if len(worldseeds) == 1:
  445.        
  446.         #TODO slimes
  447.        
  448.         if args.sv == None:
  449.             kernel += ("""
  450. __kernel void test_villageseeds(
  451.     const long magicbase,
  452.     const char asTimestamp,
  453.     __global volatile long *hits,
  454.     __global volatile uint *count
  455. ) {
  456.     long magic = magicbase + get_global_id(0);
  457.     long rand;
  458.     int bits, val, val2;
  459.    
  460. """) + "\n".join(("""
  461.     rand = ((%dL + magic) ^ 0x5deece66dL) & ((1L << 48) - 1);
  462.     do {
  463.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  464.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  465.         val = bits %% 24;
  466.     } while (bits - val + (24 - 1) < 0);
  467.     if (val != %d)
  468.         return;
  469.     do {
  470.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  471.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  472.         val = bits %% 24;
  473.     } while (bits - val + (24 - 1) < 0);
  474.     if (val != %d)
  475.         return;
  476. """ % (getVillageChunkHash(worldseeds[0],cx,cz,0),cx%32,cz%32)) for cx,cz in villagechunks) + ("""
  477.    
  478.     val = (int) atomic_inc(count);
  479.     if ((val >= 0 && val < 16)) {
  480.         hits[val] = magic;
  481.     } else {
  482.         atomic_xchg(count, 16);
  483.     }
  484. }
  485. """)
  486.         #if no sv
  487.        
  488.         if args.sf == None:
  489.             kernel += ("""
  490. __kernel void test_featureseeds(
  491.     const long magicbase,
  492.     const char asTimestamp,
  493.     __global volatile long *hits,
  494.     __global volatile uint *count
  495. ) {
  496.     long magic = magicbase + get_global_id(0);
  497.     long rand;
  498.     int bits, val, val2;
  499.    
  500. """) + "\n".join(("""
  501.     rand = ((%dL + magic) ^ 0x5deece66dL) & ((1L << 48) - 1);
  502.     do {
  503.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  504.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  505.         val = bits %% 24;
  506.     } while (bits - val + (24 - 1) < 0);
  507.     if (val != %d)
  508.         return;
  509.     do {
  510.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  511.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  512.         val = bits %% 24;
  513.     } while (bits - val + (24 - 1) < 0);
  514.     if (val != %d)
  515.         return;
  516. """ % (getFeatureChunkHash(worldseeds[0],cx,cz,0),cx%32,cz%32)) for cx,cz in featurechunks) + ("""
  517.    
  518.     val = (int) atomic_inc(count);
  519.     if ((val >= 0 && val < 16)) {
  520.         hits[val] = magic;
  521.     } else {
  522.         atomic_xchg(count, 16);
  523.     }
  524. }
  525. """)
  526.         #if no sf
  527.        
  528.         if args.sm == None:
  529.             kernel += ("""
  530. __kernel void test_monumentseeds(
  531.     const long magicbase,
  532.     const char asTimestamp,
  533.     __global volatile long *hits,
  534.     __global volatile uint *count
  535. ) {
  536.     long magic = magicbase + get_global_id(0);
  537.     long rand;
  538.     int bits, val, val2;
  539.    
  540. """) + "\n".join(("""
  541.     rand = ((%dL + magic) ^ 0x5deece66dL) & ((1L << 48) - 1);
  542.     do {
  543.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  544.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  545.         val = bits %% 27;
  546.     } while (bits - val + (27 - 1) < 0);
  547.     do {
  548.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  549.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  550.         val2 = bits %% 27;
  551.     } while (bits - val2 + (27 - 1) < 0);
  552.     if ((val + val2) / 2 != %d)
  553.         return;
  554.     do {
  555.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  556.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  557.         val = bits %% 27;
  558.     } while (bits - val + (27 - 1) < 0);
  559.     do {
  560.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  561.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  562.         val2 = bits %% 27;
  563.     } while (bits - val2 + (27 - 1) < 0);
  564.     if ((val + val2) / 2 != %d)
  565.         return;
  566. """ % (getMonumentChunkHash(worldseeds[0],cx,cz,0),cx%32,cz%32)) for cx,cz in monumentchunks) + ("""
  567.    
  568.     val = (int) atomic_inc(count);
  569.     if ((val >= 0 && val < 16)) {
  570.         hits[val] = magic;
  571.     } else {
  572.         atomic_xchg(count, 16);
  573.     }
  574. }
  575. """)
  576.         #if no sm
  577.        
  578.         if args.se == None:
  579.             kernel += ("""
  580. __kernel void test_endcityseeds(
  581.     const long magicbase,
  582.     const char asTimestamp,
  583.     __global volatile long *hits,
  584.     __global volatile uint *count
  585. ) {
  586.     long magic = magicbase + get_global_id(0);
  587.     long rand;
  588.     int bits, val, val2;
  589.    
  590. """) + "\n".join(("""
  591.     rand = ((%dL + magic) ^ 0x5deece66dL) & ((1L << 48) - 1);
  592.     do {
  593.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  594.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  595.         val = bits %% 9;
  596.     } while (bits - val + (9 - 1) < 0);
  597.     do {
  598.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  599.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  600.         val2 = bits %% 9;
  601.     } while (bits - val2 + (9 - 1) < 0);
  602.     if ((val + val2) / 2 != %d)
  603.         return;
  604.     do {
  605.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  606.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  607.         val = bits %% 9;
  608.     } while (bits - val + (9 - 1) < 0);
  609.     do {
  610.         rand = (rand * 0x5deece66dL + 0xbL) & ((1L << 48) - 1);
  611.         bits = (int)((rand >> (48 - 31)) & ((1L << 31) - 1));
  612.         val2 = bits %% 9;
  613.     } while (bits - val2 + (9 - 1) < 0);
  614.     if ((val + val2) / 2 != %d)
  615.         return;
  616. """ % (getEndCityChunkHash(worldseeds[0],cx,cz,0),cx%20,cz%20)) for cx,cz in endcitychunks) + ("""
  617.    
  618.     val = (int) atomic_inc(count);
  619.     if ((val >= 0 && val < 16)) {
  620.         hits[val] = magic;
  621.     } else {
  622.         atomic_xchg(count, 16);
  623.     }
  624. }
  625. """)
  626.         #if no se
  627.        
  628.     #if 1 worldseed
  629.    
  630.     deviceIDs = set(itertools.chain(*args.devices))
  631.     mydevices = list()
  632.     if deviceIDs:
  633.         d = 0
  634.         for platform in pyopencl.get_platforms():
  635.             for device in platform.get_devices():
  636.                 d += 1
  637.                 if d in deviceIDs:
  638.                     mydevices.append(device)
  639.         if not mydevices:
  640.             sys.exit("ERROR: The specified OpenCL device(s) were not found; refer to --list-devices")
  641.         context = pyopencl.Context(devices=mydevices)
  642.     else:
  643.         context = pyopencl.create_some_context()
  644.     queue = pyopencl.CommandQueue(context)
  645.     program = pyopencl.Program(context, kernel).build()
  646.     hits = numpy.zeros(16, dtype=numpy.int64)
  647.     count = numpy.zeros(1, dtype=numpy.uint32)
  648.     hitsBuf = pyopencl.Buffer(context, pyopencl.mem_flags.WRITE_ONLY | pyopencl.mem_flags.COPY_HOST_PTR, hostbuf=hits)
  649.     countBuf = pyopencl.Buffer(context, pyopencl.mem_flags.READ_WRITE | pyopencl.mem_flags.COPY_HOST_PTR, hostbuf=count)
  650.    
  651.     if (args.ss == None) or (args.sv == None) or (args.sf == None) or (args.sm == None) or (args.se == None):
  652.        
  653.         # TODO slimes
  654.        
  655.         if args.sv == None:
  656.             if len(worldseeds) != 1:
  657.                 sys.exit("ERROR: village seed search requires exactly one world seed")
  658.             if not villagechunks:
  659.                 sys.exit("ERROR: village seed search requires at least one village location")
  660.             print("Searching for 32-bit village seed with world seed %d ..." % (worldseeds[0],))
  661.             results = set()
  662.             t0 = time.time()
  663.             for magicbase in [0, ((1<<17)-1)]:
  664.                 event = program.test_villageseeds(queue, (1<<31,), None, numpy.int64(magicbase*(1<<31)), numpy.int8(0), hitsBuf, countBuf)
  665.                 event.wait()
  666.             pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  667.             if count[0]:
  668.                 pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  669.                 found = set(hits[h] for h in range(min(16,count[0])))
  670.                 for s in sorted(found):
  671.                     print("  Match: %d" % (s,))
  672.                 results.update(found)
  673.                 count[0] = 0
  674.                 pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  675.             t1 = time.time()
  676.             print("... OK: Search completed in %s, found %d matches" % (timeToString(t1-t0),len(results)))
  677.         #if village seed search
  678.        
  679.         if args.sf == None:
  680.             if len(worldseeds) != 1:
  681.                 sys.exit("ERROR: feature seed search requires exactly one world seed")
  682.             if not featurechunks:
  683.                 sys.exit("ERROR: feature seed search requires at least one feature location")
  684.             print("Searching for 32-bit feature seed with world seed %d ..." % (worldseeds[0],))
  685.             results = set()
  686.             t0 = time.time()
  687.             for magicbase in [0, ((1<<17)-1)]:
  688.                 event = program.test_featureseeds(queue, (1<<31,), None, numpy.int64(magicbase*(1<<31)), numpy.int8(0), hitsBuf, countBuf)
  689.                 event.wait()
  690.             pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  691.             if count[0]:
  692.                 pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  693.                 found = set(hits[h] for h in range(min(16,count[0])))
  694.                 for s in sorted(found):
  695.                     print("  Match: %d" % (s,))
  696.                 results.update(found)
  697.                 count[0] = 0
  698.                 pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  699.             t1 = time.time()
  700.             print("... OK: Search completed in %s, found %d matches" % (timeToString(t1-t0),len(results)))
  701.         #if feature seed search
  702.        
  703.         if args.sm == None:
  704.             if len(worldseeds) != 1:
  705.                 sys.exit("ERROR: monument seed search requires exactly one world seed")
  706.             if not monumentchunks:
  707.                 sys.exit("ERROR: monument seed search requires at least one monument location")
  708.             print("Searching for 32-bit monument seed with world seed %d ..." % (worldseeds[0],))
  709.             results = set()
  710.             t0 = time.time()
  711.             for magicbase in [0, ((1<<17)-1)]:
  712.                 event = program.test_monumentseeds(queue, (1<<31,), None, numpy.int64(magicbase*(1<<31)), numpy.int8(0), hitsBuf, countBuf)
  713.                 event.wait()
  714.             pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  715.             if count[0]:
  716.                 pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  717.                 found = set(hits[h] for h in range(min(16,count[0])))
  718.                 for s in sorted(found):
  719.                     print("  Match: %d" % (s,))
  720.                 results.update(found)
  721.                 count[0] = 0
  722.                 pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  723.             t1 = time.time()
  724.             print("... OK: Search completed in %s, found %d matches" % (timeToString(t1-t0),len(results)))
  725.         #if monument seed search
  726.        
  727.         if args.se == None:
  728.             if len(worldseeds) != 1:
  729.                 sys.exit("ERROR: end city seed search requires exactly one world seed")
  730.             if not endcitychunks:
  731.                 sys.exit("ERROR: end city seed search requires at least one end city location")
  732.             print("Searching for 32-bit end city seed with world seed %d ..." % (worldseeds[0],))
  733.             results = set()
  734.             t0 = time.time()
  735.             for magicbase in [0, ((1<<17)-1)]:
  736.                 event = program.test_endcityseeds(queue, (1<<31,), None, numpy.int64(magicbase*(1<<31)), numpy.int8(0), hitsBuf, countBuf)
  737.                 event.wait()
  738.             pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  739.             if count[0]:
  740.                 pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  741.                 found = set(hits[h] for h in range(min(16,count[0])))
  742.                 for s in sorted(found):
  743.                     print("  Match: %d" % (s,))
  744.                 results.update(found)
  745.                 count[0] = 0
  746.                 pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  747.             t1 = time.time()
  748.             print("... OK: Search completed in %s, found %d matches" % (timeToString(t1-t0),len(results)))
  749.         #if endcity seed search
  750.        
  751.     elif worldseeds:
  752.        
  753.         print("Validating provided world seeds and locations using OpenCL logic ...")
  754.         for s in worldseeds:
  755.             event = program.test_seeds(queue, (1,), None, numpy.int64(s), numpy.int8(0), hitsBuf, countBuf)
  756.             event.wait()
  757.             pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  758.             if count[0]:
  759.                 pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  760.                 assert(count[0] == 1)
  761.                 assert(hits[0] == s)
  762.                 print("  %d matches all criteria" % (s,))
  763.                 count[0] = 0
  764.                 pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  765.             else:
  766.                 print("  %d does not match all criteria" % (s,))
  767.         print("... OK")
  768.        
  769.     else:
  770.        
  771.         if not (slimechunks or villagechunks or monumentchunks or mansionchunks or featurechunks or endcitychunks):
  772.             sys.exit("ERROR: world seed search requires at least one slime, village, monument, mansion, feature or end city location (preferably a dozen or more)")
  773.         results = set()
  774.         pct = -1
  775.        
  776.         if not args.resume:
  777.             print("Searching for 32-bit (string-derived) world seed suffix ...")
  778.             t0 = time.time()
  779.             for seedbase in [0, ((1<<17)-1)]:
  780.                 event = program.test_seeds(queue, (1<<31,), None, numpy.int64(seedbase*(1<<31)), numpy.int8(0), hitsBuf, countBuf)
  781.                 event.wait()
  782.             pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  783.             if count[0]:
  784.                 pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  785.                 found = set(hits[h] for h in range(min(16,count[0])))
  786.                 for s in sorted(found):
  787.                     print("  Match: %d" % (s,))
  788.                 results.update(found)
  789.                 count[0] = 0
  790.                 pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  791.             t1 = time.time()
  792.             print("... OK: Search completed in %s, found %d matches so far" % (timeToString(t1-t0),len(results)))
  793.            
  794.             """
  795. DISABLED timestamp-derived scan; newer JDK uses System.nanoTime() and a secondary Uniquifier() which depends on how many instances of Random() have ever been created
  796.             print("Searching for ~38-bit (timestamp-derived) world seed suffix ...")
  797.             t0 = time.time()
  798.             for seedbase in range(587, int((t0+60*60*24*10) * 1000 / (1<<31))+1): # milliseconds from 1970-01-01 to 2010-01-01 = 1262300400876 ~= 587.8 * 2^31
  799.                 event = program.test_seeds(queue, (1<<31,), None, numpy.int64(seedbase*(1<<31)), numpy.int8(1), hitsBuf, countBuf)
  800.                 event.wait()
  801.             pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  802.             if count[0]:
  803.                 pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  804.                 found = set(hits[h] for h in range(min(16,count[0])))
  805.                 for s in sorted(found):
  806.                     print("  Match: %d" % (s,))
  807.                 results.update(found)
  808.                 count[0] = 0
  809.                 pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  810.             t1 = time.time()
  811.             print("... OK: Search completed in %s, found %d matches so far" % (timeToString(t1-t0),len(results)))
  812. """
  813.         #if not resume
  814.        
  815.         print("Searching for 48-bit world seed suffix (ctrl-c to stop) ...")
  816.         t0 = time.time()
  817.         pct = 1000 * args.resume // (1<<17)
  818.         seedbase = args.resume or 1
  819.         while seedbase < ((1<<17)-1):
  820.             try:
  821.                 event = program.test_seeds(queue, (1<<31,), None, numpy.int64(seedbase*(1<<31)), numpy.int8(0), hitsBuf, countBuf)
  822.                 event.wait()
  823.                 if pct != 1000 * seedbase // (1<<17):
  824.                     pct = 1000 * seedbase // (1<<17)
  825.                     pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  826.                     if count[0]:
  827.                         pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  828.                         found = set(hits[h] for h in range(min(16,count[0])))
  829.                         for s in sorted(found):
  830.                             print("  Match: %d" % (s,))
  831.                         results.update(found)
  832.                         count[0] = 0
  833.                         pyopencl.enqueue_copy(queue, countBuf, count, is_blocking=True)
  834.                     t1 = time.time()
  835.                     print("... %d result(s) after %s, %.1f%% complete, ~%s to go ..." % (
  836.                             len(results),
  837.                             timeToString(t1-t0),
  838.                             100.0*seedbase/(1<<17),
  839.                             timeToString(((float((1<<17) - args.resume) / (seedbase - args.resume)) * (t1 - t0)) - (t1 - t0))
  840.                     ))
  841.                 seedbase += 1
  842.                 continue
  843.             except KeyboardInterrupt:
  844.                 pass
  845.            
  846.             t1 = time.time()
  847.             try:
  848.                 input("... PAUSED. Press ENTER to continue, or ctrl-c to exit.")
  849.                 t0 += (time.time() - t1)
  850.                 print("Resuming 48-bit world seed suffix search (ctrl-c to stop) ...")
  851.                 seedbase -= 1
  852.                 continue
  853.             except (EOFError, KeyboardInterrupt) as e:
  854.                 pass
  855.            
  856.             try:
  857.                 print("\n... OK: Search aborted after %s, resume with --resume %d" % (timeToString(t1-t0), max(args.resume,seedbase-1)))
  858.             except (EOFError, KeyboardInterrupt) as e:
  859.                 pass
  860.            
  861.             seedbase = -1
  862.             break
  863.         #while
  864.         t1 = time.time()
  865.         if seedbase >= 0:
  866.             print("... OK: Search completed in %s" % (timeToString(t1-t0),))
  867.         pyopencl.enqueue_copy(queue, count, countBuf, is_blocking=True)
  868.         pyopencl.enqueue_copy(queue, hits, hitsBuf, is_blocking=True)
  869.         results.update(hits[h] for h in range(min(16,count[0])))
  870.         print("Final results:")
  871.         for s in sorted(results):
  872.             print("  %d" % (s,))
  873.         print("... OK: %d matches" % (len(results),))
  874.     #if worldseeds
  875.    
  876. #if __main__
Add Comment
Please, Sign In to add comment