├── .gitignore
├── Forge.py
├── LICENSE
├── README.md
├── configs.py
├── experiments.py
├── figures.py
├── forge
├── __init__.py
├── blade
│ ├── __init__.py
│ ├── action
│ │ ├── action.py
│ │ ├── tree.py
│ │ └── v2.py
│ ├── core
│ │ ├── __init__.py
│ │ ├── config.py
│ │ ├── env.py
│ │ ├── map.py
│ │ ├── realm.py
│ │ └── tile.py
│ ├── entity
│ │ ├── __init__.py
│ │ ├── entity.py
│ │ ├── npc
│ │ │ ├── __init__.py
│ │ │ ├── mobs.py
│ │ │ └── npc.py
│ │ └── player.py
│ ├── hook
│ │ ├── __init__.py
│ │ ├── item.py
│ │ └── modules.py
│ ├── item
│ │ ├── __init__.py
│ │ ├── armor.py
│ │ ├── food.py
│ │ ├── item.py
│ │ ├── knife.py
│ │ ├── ore.py
│ │ ├── rawfish.py
│ │ ├── rawmeat.py
│ │ ├── sword.py
│ │ └── tool.py
│ ├── lib
│ │ ├── __init__.py
│ │ ├── comms.py
│ │ ├── enums.py
│ │ ├── log.py
│ │ ├── multiset.py
│ │ ├── priorityqueue.py
│ │ ├── ray.py
│ │ ├── stattrak.py
│ │ └── utils.py
│ └── systems
│ │ ├── __init__.py
│ │ ├── ai.py
│ │ ├── combat.py
│ │ ├── droptable.py
│ │ ├── equipment.py
│ │ ├── exchange.py
│ │ ├── experience.py
│ │ ├── inventory.py
│ │ ├── recipe.py
│ │ └── skill.py
├── embyr
├── ethyr
│ ├── rollouts.py
│ ├── stim.py
│ └── torch
│ │ ├── __init__.py
│ │ ├── loss.py
│ │ ├── optim.py
│ │ ├── param.py
│ │ ├── policy.py
│ │ ├── save.py
│ │ ├── stim.py
│ │ └── utils.py
└── trinity
│ ├── __init__.py
│ ├── ann.py
│ ├── god.py
│ ├── pantheon.py
│ ├── smith.py
│ ├── sword.py
│ └── trinity.py
├── jsuarez
├── Baselines.py
├── BatchSnippets.py
├── CPUUtils.py
├── Color256.py
├── ColorEnts.py
├── Curiosity.py
├── Desciple.py
├── ES.py
├── Handler.py
├── MPIUtils.py
├── MapMaker.py
├── NPCHandler.py
├── PC.py
├── PCHandler.py
├── SkillActions.py
├── extra
│ ├── embyr_deprecated
│ │ ├── embyr
│ │ │ ├── EnvViewport3D.py
│ │ │ ├── __init__.py
│ │ │ ├── application.py
│ │ │ ├── block.mtl
│ │ │ ├── block.obj
│ │ │ ├── blocks.png
│ │ │ ├── client.py
│ │ │ ├── embyr.py
│ │ │ ├── embyr3D.py
│ │ │ ├── enums.py
│ │ │ ├── example1.py
│ │ │ ├── example2.py
│ │ │ ├── examplecust.py
│ │ │ ├── examples
│ │ │ │ ├── camera
│ │ │ │ │ └── main.py
│ │ │ │ ├── createscene.py
│ │ │ │ ├── example1.py
│ │ │ │ ├── example2.py
│ │ │ │ ├── example3.py
│ │ │ │ ├── monkey.py
│ │ │ │ ├── textures
│ │ │ │ │ └── main.py
│ │ │ │ └── trackball
│ │ │ │ │ └── main.py
│ │ │ ├── kivy3
│ │ │ │ ├── __init__.py
│ │ │ │ ├── cameras
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ ├── camera.py
│ │ │ │ │ ├── orthographic_camera.py
│ │ │ │ │ └── perspective_camera.py
│ │ │ │ ├── core
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ ├── face3.py
│ │ │ │ │ ├── geometry.py
│ │ │ │ │ └── object3d.py
│ │ │ │ ├── extras
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ └── geometries.py
│ │ │ │ ├── loaders
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ ├── loader.py
│ │ │ │ │ └── objloader.py
│ │ │ │ ├── materials.py
│ │ │ │ ├── math
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ └── vectors.py
│ │ │ │ ├── objects
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ └── mesh.py
│ │ │ │ ├── renderer.py
│ │ │ │ └── scenes
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ └── scene.py
│ │ │ ├── modules.py
│ │ │ ├── oldapp.py
│ │ │ ├── oldnewapi.py
│ │ │ ├── oldtrans.py
│ │ │ ├── render.py
│ │ │ ├── setup.py
│ │ │ ├── tests
│ │ │ │ ├── __init__.py
│ │ │ │ ├── core
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ └── test_object3d.py
│ │ │ │ ├── loaders
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ ├── test_loader.py
│ │ │ │ │ └── test_objloader.py
│ │ │ │ ├── test_materials.py
│ │ │ │ ├── test_vectors.py
│ │ │ │ └── utils.py
│ │ │ ├── tex
│ │ │ │ ├── black.png
│ │ │ │ ├── blinn-phong.glsl
│ │ │ │ ├── default.glsl
│ │ │ │ ├── dirt.png
│ │ │ │ ├── forest.png
│ │ │ │ ├── grass.png
│ │ │ │ ├── lava.png
│ │ │ │ ├── map.tmx
│ │ │ │ ├── nn.mtl
│ │ │ │ ├── nn.obj
│ │ │ │ ├── simple.glsl
│ │ │ │ ├── stone.png
│ │ │ │ ├── water.png
│ │ │ │ └── white.png
│ │ │ ├── texture.py
│ │ │ ├── transform.py
│ │ │ └── utils.py
│ │ └── embyr2d
│ │ │ ├── __init__.py
│ │ │ ├── application.py
│ │ │ ├── embyr.py
│ │ │ ├── modules.py
│ │ │ ├── render.py
│ │ │ ├── texture.py
│ │ │ └── utils.py
│ ├── envfig.py
│ ├── envgif.py
│ ├── figures.py
│ ├── makeTourney.py
│ ├── plottourney.py
│ └── returns.py
├── log.sh
├── map
│ ├── edge.png
│ ├── edge.txt
│ ├── edgeville.txt
│ ├── fullmap.png
│ ├── fullmap.txt
│ ├── largemap.png
│ ├── largemap.txt
│ ├── map.png
│ ├── medmap.png
│ ├── medmap.txt
│ ├── oldfull.png
│ ├── oldfull.txt
│ ├── profmap.png
│ ├── profmap.txt
│ ├── profs.png
│ ├── profs.txt
│ ├── smallmap.png
│ ├── smallmap.txt
│ └── testmap.txt
├── quote.txt
├── reset.sh
├── todo.txt
└── tools
│ ├── ColorEnts.py
│ ├── ColorTransform.py
│ ├── Colors.py
│ ├── GPUTest.py
│ ├── MapMaker.py
│ ├── RayTest.py
│ ├── RenderTest.py
│ ├── SeedTest.py
│ ├── TensorboardExample.py
│ ├── TestDropbox.py
│ ├── TestGA.py
│ ├── Tests.py
│ ├── VideoLog.py
│ ├── codesize.sh
│ ├── gl.py
│ ├── handletest.py
│ ├── kiv.py
│ └── test.py
├── logs.py
├── resource
├── assets
│ ├── action
│ │ ├── mage.png
│ │ ├── mageattack.png
│ │ ├── melee.png
│ │ ├── meleeattack.png
│ │ ├── range.png
│ │ └── rangeattack.png
│ ├── entity
│ │ ├── chicken.png
│ │ ├── goblin.png
│ │ ├── neural.png
│ │ ├── neuralBLUE.png
│ │ ├── neuralCYAN.png
│ │ ├── neuralFUCHSIA.png
│ │ ├── neuralGREEN.png
│ │ ├── neuralMAGENTA.png
│ │ ├── neuralMINT.png
│ │ ├── neuralORANGE.png
│ │ ├── neuralPURPLE.png
│ │ ├── neuralRED.png
│ │ ├── neuralSKY.png
│ │ ├── neuralSPRING.png
│ │ └── neuralYELLOW.png
│ ├── fonts
│ │ └── dragonslapper.ttf
│ ├── splash
│ │ └── splash.png
│ └── tiles
│ │ ├── .DS_Store
│ │ ├── brick.png
│ │ ├── clay.png
│ │ ├── coal_ore.png
│ │ ├── cobblestone.png
│ │ ├── dirt.png
│ │ ├── forest.png
│ │ ├── grass.png
│ │ ├── grass_side.png
│ │ ├── gravel.png
│ │ ├── ice.png
│ │ ├── iron_ore.png
│ │ ├── lava.png
│ │ ├── lavaold.png
│ │ ├── planks_oak.png
│ │ ├── sand.png
│ │ ├── sandstone.png
│ │ ├── scrub.png
│ │ ├── snow.png
│ │ ├── stone.png
│ │ ├── tree.png
│ │ └── water.png
├── docs
│ ├── ags.png
│ ├── air.png
│ ├── air_thumbnail.png
│ ├── early_demo.mp4
│ ├── earth.png
│ ├── earth_thumbnail.png
│ ├── env.jpg
│ ├── equipment.png
│ ├── fire.png
│ ├── fire_thumbnail.png
│ ├── logo.png
│ ├── logodark.png
│ ├── map.png
│ ├── neural.png
│ ├── neuralBLUE.png
│ ├── neuralCYAN.png
│ ├── neuralFUCHSIA.png
│ ├── neuralGREEN.png
│ ├── neuralMAGENTA.png
│ ├── neuralMINT.png
│ ├── neuralORANGE.png
│ ├── neuralPURPLE.png
│ ├── neuralRED.png
│ ├── neuralSKY.png
│ ├── neuralSPRING.png
│ ├── neuralYELLOW.png
│ ├── quests.png
│ ├── skills.png
│ ├── water.png
│ └── water_thumbnail.png
├── exps
│ ├── sample-autotarget
│ │ ├── model
│ │ │ └── bests.pth
│ │ └── train
│ │ │ ├── counts_forest.png
│ │ │ ├── counts_grass.png
│ │ │ ├── counts_scrub.png
│ │ │ ├── explore_grass.png
│ │ │ ├── explore_scrub.png
│ │ │ ├── lifetime.png
│ │ │ ├── reward.png
│ │ │ ├── unique_forest.png
│ │ │ ├── unique_grass.png
│ │ │ ├── unique_scrub.png
│ │ │ └── value.png
│ └── testchaos128
│ │ └── model
│ │ └── bests.pth
├── logs
│ └── .gitignore
└── maps
│ ├── fixed
│ ├── br.tmx
│ ├── testmap.tmx
│ └── v1full.tmx
│ ├── procedural
│ └── .gitignore
│ ├── testtileset.tsx
│ ├── tiles.tsx
│ └── tileset.tsx
├── scripts
└── setup
│ ├── __init__.py
│ ├── requirements.txt
│ └── setup.sh
├── setup.py
├── terrain.py
└── v1.2.png
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 |
--------------------------------------------------------------------------------
/Forge.py:
--------------------------------------------------------------------------------
1 | #Main file. Hooks into high level world/render updates
2 | from pdb import set_trace as T
3 | import argparse
4 |
5 | import experiments
6 | from forge.trinity import smith, Trinity, Pantheon, God, Sword
7 |
8 | def parseArgs():
9 | parser = argparse.ArgumentParser('Projekt Godsword')
10 | parser.add_argument('--nRealm', type=int, default='1',
11 | help='Number of environments (1 per core)')
12 | parser.add_argument('--api', type=str, default='native',
13 | help='API to use (native/vecenv)')
14 | parser.add_argument('--ray', type=str, default='default',
15 | help='Ray mode (local/default/remote)')
16 | parser.add_argument('--render', action='store_true', default=False,
17 | help='Render env')
18 | return parser.parse_args()
19 |
20 | #Example runner using the (slower) vecenv api
21 | #The actual vecenv spec was not designed for
22 | #multiagent, so this is a best-effort facsimile
23 | class GymExample:
24 | def __init__(self, config, args):
25 | self.env = smith.VecEnv(config, args, self.step)
26 | #The environment is persistent. Reset only to start it.
27 | self.envsObs = self.env.reset()
28 |
29 | #the ANN used internally by Trinity
30 | from forge.trinity import ANN
31 | self.ann = ANN(config)
32 |
33 | #Runs a single step of each environment
34 | #With slow comms at each step
35 | def step(self):
36 | actions = []
37 | for obs in self.envsObs: #Environment
38 | atns = []
39 | for ob in obs: #Agent
40 | ent, stim = ob
41 | action, arguments, atnArgs, val = self.ann(ent, stim)
42 | atns.append((ent.entID, action, arguments, float(val)))
43 | actions.append(atns)
44 | self.envsObs, rews, dones, infos = self.env.step(actions)
45 |
46 | def run(self):
47 | while True:
48 | self.step()
49 |
50 | class NativeExample:
51 | def __init__(self, config, args):
52 | trinity = Trinity(Pantheon, God, Sword)
53 | self.env = smith.Native(config, args, trinity)
54 |
55 | def run(self):
56 | while True:
57 | self.env.run()
58 |
59 | if __name__ == '__main__':
60 | args = parseArgs()
61 | assert args.api in ('native', 'vecenv')
62 | config = experiments.exps['testchaos128']
63 |
64 | if args.api == 'native':
65 | example = NativeExample(config, args)
66 | elif args.api == 'vecenv':
67 | example = GymExample(config, args)
68 |
69 | #Rendering by necessity snags control flow
70 | #This will automatically set local mode with 1 core
71 | if args.render:
72 | example.env.render()
73 |
74 | example.run()
75 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 OpenAI
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/configs.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from forge.blade.core.config import Config
3 | from forge.blade.lib import utils
4 | import numpy as np
5 |
6 | class Experiment(Config):
7 | def defaults(self):
8 | super().defaults()
9 | self.MODELDIR='resource/logs/'
10 | self.HIDDEN = 32
11 | self.TEST = False
12 | self.LOAD = False
13 | self.BEST = False
14 | self.SAMPLE = False
15 | self.NATTN = 2
16 | self.NPOP = 1
17 | self.SHAREINIT = False
18 | self.ENTROPY = 0.01
19 | self.VAMPYR = 1
20 | self.AUTO_TARGET = False
21 |
22 | #Foraging only
23 | class Law(Experiment):
24 | def defaults(self):
25 | super().defaults()
26 |
27 | #Damage
28 | def MELEEDAMAGE(self, ent, targ): return 0
29 | def RANGEDAMAGE(self, ent, targ): return 0
30 | def MAGEDAMAGE(self, ent, targ): return 0
31 |
32 | #Foraging + Combat
33 | class Chaos(Experiment):
34 | def defaults(self):
35 | super().defaults()
36 | self.RANGERANGE = 2
37 | self.MAGERANGE = 3
38 |
39 | def vamp(self, ent, targ, frac, dmg):
40 | dmg = int(frac * dmg)
41 | targ.food.decrement(amt=dmg)
42 | targ.water.decrement(amt=dmg)
43 | ent.food.increment(amt=dmg)
44 | ent.water.increment(amt=dmg)
45 |
46 | #Damage formulas. Lambdas don't pickle well
47 | def MELEEDAMAGE(self, ent, targ):
48 | dmg = 10
49 | targ.applyDamage(dmg)
50 | self.vamp(ent, targ, self.VAMPYR, dmg)
51 | return dmg
52 |
53 | def RANGEDAMAGE(self, ent, targ):
54 | dmg = 2
55 | targ.applyDamage(dmg)
56 | self.vamp(ent, targ, self.VAMPYR, dmg)
57 | return dmg
58 |
59 | def MAGEDAMAGE(self, ent, targ):
60 | dmg = 1
61 | targ.applyDamage(dmg)
62 | self.vamp(ent, targ, self.VAMPYR, dmg)
63 | return dmg
64 |
--------------------------------------------------------------------------------
/experiments.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from configs import Law, Chaos
3 | import os
4 |
5 | #Oversimplified user specification
6 | #for 1-3 collaborators
7 | USER = 'your-username'
8 | if USER == 'your-username':
9 | #Thousandth
10 | prefix = 'test'
11 | remote = False
12 | local = not remote
13 |
14 | test = True#local
15 | best = True#local
16 | load = True#local
17 |
18 | sample = not test
19 | singles = True
20 | tournaments = False
21 |
22 | exps = {}
23 | szs = [128]
24 | #For full distributed runs
25 | #szs = (16, 32, 64, 128)
26 | names = 'law chaos'.split()
27 | confs = (Law, Chaos)
28 |
29 | def makeExp(name, conf, sz, test=False):
30 | NENT, NPOP = sz, sz//16
31 | ROOT = 'resource/exps/' + name + '/'
32 | try:
33 | os.mkdir(ROOT)
34 | os.mkdir(ROOT + 'model')
35 | os.mkdir(ROOT + 'train')
36 | os.mkdir(ROOT + 'test')
37 | except FileExistsError:
38 | pass
39 | MODELDIR = ROOT + 'model/'
40 |
41 | exp = conf(remote,
42 | NENT=NENT, NPOP=NPOP,
43 | MODELDIR=MODELDIR,
44 | SAMPLE=sample,
45 | BEST=best,
46 | LOAD=load,
47 | TEST=test)
48 | exps[name] = exp
49 | print(name, ', NENT: ', NENT, ', NPOP: ', NPOP)
50 |
51 | def makeExps():
52 | #Training runs
53 | for label, conf in zip(names, confs):
54 | for sz in szs:
55 | name = prefix + label + str(sz)
56 | makeExp(name, conf, sz, test=test)
57 |
58 | #Sample config
59 | makeExps()
60 | makeExp('sample', Chaos, 128, test=True)
61 |
--------------------------------------------------------------------------------
/forge/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/forge/__init__.py
--------------------------------------------------------------------------------
/forge/blade/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/forge/blade/__init__.py
--------------------------------------------------------------------------------
/forge/blade/action/action.py:
--------------------------------------------------------------------------------
1 | class Pass:
2 | pass
3 |
4 | class Move:
5 | pass
6 |
7 | class Reproduce:
8 | pass
9 |
10 | class Attack:
11 | pass
12 |
13 | class Range(Attack):
14 | pass
15 |
16 | class Mage(Attack):
17 | pass
18 |
19 | class Melee(Attack):
20 | pass
21 |
22 | class Skill:
23 | pass
24 |
25 | class Harvest:
26 | pass
27 |
28 | class Fish:
29 | pass
30 |
31 | class Mine:
32 | pass
33 |
34 | class Process:
35 | pass
36 |
37 | class Cook:
38 | pass
39 |
40 | class Smith:
41 | pass
42 |
43 | class Exchange:
44 | pass
45 |
46 | class Buy:
47 | pass
48 |
49 | class Sell:
50 | pass
51 |
52 | class CancelOffer:
53 | pass
54 |
55 | class Message:
56 | pass
57 |
--------------------------------------------------------------------------------
/forge/blade/action/tree.py:
--------------------------------------------------------------------------------
1 | class ActionNode:
2 | def edges(self, world, entity):
3 | pass
4 |
5 | class ActionLeaf(ActionNode):
6 | def __call__(self, world, entity, *args):
7 | if type(args) == EmptyArgs:
8 | args = []
9 |
10 | class Args:
11 | isEmpty = False
12 | isSet = False
13 | isDiscrete = False
14 | def __init__(self, value=None):
15 | self.value = value
16 |
17 | class Arg(Args): pass
18 |
19 | class SetArgs(Args):
20 | isSet = True
21 |
22 | def __init__(self):
23 | self.setValue = set()
24 |
25 | def add(self, value):
26 | self.setValue.add(value)
27 |
28 | def toList(self):
29 | return list(self.setValue)
30 |
31 | @property
32 | def empty(self):
33 | return len(self.toList()) == 0
34 |
35 | class DiscreteArgs(SetArgs):
36 | isDiscrete = True
37 |
38 | class EmptyArgs(Args):
39 | isEmpty = True
40 |
41 | class ActionTree:
42 | def __init__(self, world, entity, rootVersion):
43 | self.world, self.entity = world, entity
44 | self.root, self.args = rootVersion(), None
45 |
46 | @property
47 | def n(self):
48 | return sum([a.nArgs() for a in self.action.edges()])
49 |
50 | def flat(self):
51 | rets = []
52 | for action in self.root.edges(None, None):
53 | for args in action.args(None, None):
54 | rets.append((action, args))
55 | return rets
56 |
57 | def actions(self):
58 | return self.root.edges(None, None)
59 |
60 | def rand(self):
61 | nodes = self.flat()
62 | ind = np.random.randint(0, len(nodes))
63 | return nodes[ind]
64 |
65 | def actionArgPair(self):
66 | assert self.action is not None and self.args is not None
67 | if type(self.args) not in (list, tuple):
68 | self.args = [self.args]
69 | return type(self.action), self.args
70 |
71 |
--------------------------------------------------------------------------------
/forge/blade/core/__init__.py:
--------------------------------------------------------------------------------
1 | from .env import Env
2 | from .map import Map
3 | from .realm import VecEnvRealm, NativeRealm
4 | from .tile import Tile
5 |
--------------------------------------------------------------------------------
/forge/blade/core/config.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 |
4 | class Config:
5 | def __init__(self, remote=False, **kwargs):
6 | self.defaults()
7 | for k, v in kwargs.items():
8 | setattr(self, k, v)
9 |
10 | if remote:
11 | self.ROOT = '/root/code/Projekt-Godsword/' + self.ROOT
12 |
13 | def defaults(self):
14 | self.ROOT = 'resource/maps/procedural/map'
15 | self.SUFFIX = '/map.tmx'
16 | self.BORDER = 9
17 | self.SZ = 62
18 | self.R = self.SZ + self.BORDER
19 | self.C = self.SZ + self.BORDER
20 |
21 | self.STIM = 7
22 | self.NENT = 256
23 |
24 | #Base agent stats
25 | self.HEALTH = 10
26 | self.FOOD = 32
27 | self.WATER = 32
28 |
29 | #Attack ranges
30 | self.MELEERANGE = 1
31 | self.RANGERANGE = 4
32 | self.MAGERANGE = 4
33 |
34 | def SPAWN(self):
35 | R, C = self.R, self.C
36 | spawn, border, sz = [], self.BORDER, self.SZ
37 | spawn += [(border, border+i) for i in range(sz)]
38 | spawn += [(border+i, border) for i in range(sz)]
39 | spawn += [(R-1, border+i) for i in range(sz)]
40 | spawn += [(border+i, C-1) for i in range(sz)]
41 | idx = np.random.randint(0, len(spawn))
42 | return spawn[idx]
43 |
44 | #Damage formulas. Lambdas don't pickle well
45 | def MELEEDAMAGE(self, ent, targ): return 0
46 | def RANGEDAMAGE(self, ent, targ): return 0
47 | def MAGEDAMAGE(self, ent, targ): return 0
48 |
49 |
--------------------------------------------------------------------------------
/forge/blade/core/env.py:
--------------------------------------------------------------------------------
1 | #Main world definition. Defines and manages entity handlers,
2 | #Defines behavior of the world under all circumstances and handles
3 | #interaction by agents. Also defines an accurate stimulus that
4 | #encapsulates the world as seen by a particular agent
5 |
6 | import numpy as np
7 |
8 | from forge.blade import systems
9 | from forge.blade.lib import utils
10 | from forge.blade import lib
11 |
12 | from forge.blade import core
13 | from forge.blade.item import rawfish, knife, armor
14 | from pdb import set_trace as T
15 |
16 | class Env:
17 | def __init__(self, config, idx):
18 | #Load the world file
19 | self.env = core.Map(config, idx)
20 | self.shape = self.env.shape
21 | self.spawn = config.SPAWN
22 | self.config = config
23 |
24 | #Entity handlers
25 | self.stimSize = 3
26 | self.worldDim = 2*self.stimSize+1
27 |
28 | #Exchange - For future updates
29 | self.market = systems.Exchange()
30 | sardine = rawfish.Sardine
31 | nife = knife.Iron
32 | armr = armor.Iron
33 | self.market.buy(sardine, 10, 30)
34 | self.market.sell(nife, 20, 50)
35 | self.market.buy(armr, 1, 500)
36 | self.market.sell(armr, 3, 700)
37 |
38 | self.stats = lib.StatTraker()
39 |
40 | self.tick = 0
41 | self.envTimer = utils.BenchmarkTimer()
42 | self.entTimer = utils.BenchmarkTimer()
43 | self.cpuTimer = utils.BenchmarkTimer()
44 | self.handlerTimer = utils.BenchmarkTimer()
45 | self.statTimer = utils.BenchmarkTimer()
46 |
47 | def stim(self, pos):
48 | return self.env.getPadded(self.env.tiles, pos,
49 | self.stimSize, key=lambda e:e.index).astype(np.int8)
50 |
51 | #Hook for render
52 | def graphicsData(self):
53 | return self.env, self.stats
54 |
55 | def step(self, pcs, npcs):
56 | self.stats.update(pcs, npcs, self.market)
57 | self.tick += 1
58 |
59 |
--------------------------------------------------------------------------------
/forge/blade/core/map.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 |
4 | from forge.blade import core
5 | from forge.blade.lib import enums, utils
6 |
7 | def loadTiled(fPath, tiles, nCounts):
8 | import pytmx
9 | tm = pytmx.TiledMap(fPath)
10 | assert len(tm.layers) == 1
11 | layer = tm.layers[0]
12 | W, H = layer.width, layer.height
13 | tilemap = np.zeros((H, W), dtype=object)
14 | for w, h, dat in layer.tiles():
15 | f = dat[0]
16 | tex = f.split('/')[-1].split('.')[0]
17 | tilemap[h, w] = core.Tile(tiles[tex], h, w, nCounts, tex)
18 | return tilemap
19 |
20 | class Map:
21 | def __init__(self, config, idx):
22 | self.updateList = set()
23 | self.nCounts = config.NPOP
24 | self.genEnv(config.ROOT + str(idx) + config.SUFFIX)
25 |
26 | def harvest(self, r, c):
27 | self.updateList.add(self.tiles[r, c])
28 | return self.tiles[r, c].harvest()
29 |
30 | def inds(self):
31 | return np.array([[j.state.index for j in i] for i in self.tiles])
32 |
33 | def step(self):
34 | for e in self.updateList.copy():
35 | if e.static:
36 | self.updateList.remove(e)
37 | #Perform after check: allow texture to reset
38 | e.step()
39 |
40 | def stim(self, pos, rng):
41 | r, c = pos
42 | rt, rb = r-rng, r+rng+1
43 | cl, cr = c-rng, c+rng+1
44 | return self.tiles[rt:rb, cl:cr]
45 |
46 | #Fix this function to key by attr for mat.index
47 | def getPadded(self, mat, pos, sz, key=lambda e: e):
48 | ret = np.zeros((2*sz+1, 2*sz+1), dtype=np.int32)
49 | R, C = pos
50 | rt, rb = R-sz, R+sz+1
51 | cl, cr = C-sz, C+sz+1
52 | for r in range(rt, rb):
53 | for c in range(cl, cr):
54 | if utils.inBounds(r, c, self.size):
55 | ret[r-rt, c-cl] = key(mat[r, c])
56 | else:
57 | ret[r-rt, c-cl] = 0
58 | return ret
59 |
60 | def np(self):
61 | env = np.array([e.state.index for e in
62 | self.tiles.ravel()]).reshape(*self.shape)
63 | return env
64 |
65 | def genEnv(self, fName):
66 | tiles = dict((mat.value.tex, mat.value) for mat in enums.Material)
67 | self.tiles = loadTiled(fName, tiles, self.nCounts)
68 | self.shape = self.tiles.shape
69 |
70 |
--------------------------------------------------------------------------------
/forge/blade/core/tile.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 |
4 |
5 | class Tile:
6 | def __init__(self, mat, r, c, nCounts, tex):
7 | self.r, self.c = r, c
8 | self.mat = mat()
9 | self.ents = {}
10 | self.state = mat()
11 | self.capacity = self.mat.capacity
12 | self.counts = np.zeros(nCounts)
13 | self.tex = tex
14 |
15 | @property
16 | def nEnts(self):
17 | return len(self.ents)
18 |
19 | def addEnt(self, entID, ent):
20 | assert entID not in self.ents
21 | self.ents[entID] = ent
22 |
23 | def delEnt(self, entID):
24 | assert entID in self.ents
25 | del self.ents[entID]
26 |
27 | def step(self):
28 | if (not self.static and
29 | np.random.rand() < self.mat.respawnProb):
30 | self.capacity += 1
31 | #Try inserting a pass
32 | if self.static:
33 | self.state = self.mat
34 |
35 | @property
36 | def static(self):
37 | assert self.capacity <= self.mat.capacity
38 | return self.capacity == self.mat.capacity
39 |
40 | def harvest(self):
41 | if self.capacity == 0:
42 | return False
43 | elif self.capacity <= 1:
44 | self.state = self.mat.degen()
45 | self.capacity -= 1
46 | return True
47 | return self.mat.dropTable.roll()
48 |
--------------------------------------------------------------------------------
/forge/blade/entity/__init__.py:
--------------------------------------------------------------------------------
1 | from .entity import Entity
2 | from .player import Player
3 |
--------------------------------------------------------------------------------
/forge/blade/entity/entity.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | from forge.blade.action import action
4 | from forge.blade.systems import skill, droptable
5 |
6 | class Entity():
7 | def __init__(self, pos):
8 | self.pos = pos
9 | self.alive = True
10 | self.skills = skill.Skills()
11 | self.entityIndex=0
12 | self.health = -1
13 | self.lastAttacker = None
14 |
15 | def act(self, world):
16 | pass
17 |
18 | def decide(self, stimuli):
19 | pass
20 |
21 | def death(self):
22 | pass
23 |
24 | def registerHit(self, attacker, dmg):
25 | self.lastAttacker = attacker
26 | self.health -= dmg
27 |
28 | def remove(self, ent):
29 | r, c = self.pos
30 | ent[r, c] = 0
31 |
32 | def isAlive(self):
33 | return self.health > 0
34 |
35 | @property
36 | def isPC(self):
37 | return False
38 |
--------------------------------------------------------------------------------
/forge/blade/entity/npc/__init__.py:
--------------------------------------------------------------------------------
1 | from .npc import NPC
2 |
--------------------------------------------------------------------------------
/forge/blade/entity/npc/mobs.py:
--------------------------------------------------------------------------------
1 | #NPC definitions with AI overrides per NPC, as required.
2 |
3 | from forge.blade.entity import NPC
4 | from forge.blade.item import Item, RawMeat, Sword
5 | from forge.blade.lib import AI
6 | from forge.blade.lib.Enums import Material
7 | from forge.blade.modules import DropTable, Skill
8 |
9 |
10 | class Chicken(NPC.Passive):
11 | def __init__(self, pos):
12 | super().__init__(pos)
13 | self.index = 2
14 | self.maxHealth = 5
15 | self.health = self.maxHealth
16 | self.expOnKill = 10
17 |
18 | self.drops.add(RawMeat.Chicken, 1)
19 | self.drops.add(RawMeat.Chicken, 1, 0.5)
20 |
21 | def decide(self, world):
22 | action, args = AI.randomOnTurf(world, self,
23 | [Material.GRASS.value])
24 | return action, args
25 |
26 | class Goblin(NPC.PassiveAgressive):
27 | def __init__(self, pos):
28 | super().__init__(pos)
29 | self.index = 3
30 | self.searchRange = 5
31 | self.maxHealth = 15
32 | self.health = self.maxHealth
33 | self.expOnKill = 50
34 | self.skills.melee.exp = Skill.Skill.expCalculator.expAtLevel(5)
35 | self.skills.defense.exp = Skill.Skill.expCalculator.expAtLevel(5)
36 |
37 | self.drops.add(RawMeat.Goblin, 1)
38 | self.drops.add(Item.Gold, DropTable.Range(1, 100), 0.5)
39 | self.drops.add(Sword.Copper, 1, 0.2)
40 |
41 | def decide(self, world):
42 | #action, args = AI.turfSearchAndDestroy(world, self,
43 | # whitelist=[Material.FOREST.value])
44 | action, args = AI.randomOnTurf(world, self,
45 | [Material.FOREST.value])
46 | return action, args
47 |
48 |
--------------------------------------------------------------------------------
/forge/blade/entity/npc/npc.py:
--------------------------------------------------------------------------------
1 | from sim.entity.Entity import Entity
2 | from sim.lib import Enums, AI
3 | from sim.modules import DropTable
4 |
5 |
6 | #NPC
7 | class NPC(Entity):
8 | def __init__(self, pos):
9 | super().__init__(pos)
10 | self.expOnKill = 10
11 | self.drops = DropTable.DropTable()
12 |
13 | #NPCs have direct access to the world
14 | def act(self, world):
15 | action, args = self.decide(world)
16 | if type(args) == Actions.EmptyArgs:
17 | args = []
18 | action(world, self, *args)
19 | self.lastAction = action
20 |
21 | def yieldDrops(self):
22 | self.lastAttacker.receiveDrops(self.drops.roll())
23 |
24 | #Wanders aimlessly. Ignores attacks
25 | class Passive(NPC):
26 | def __init__(self, pos):
27 | super().__init__(pos)
28 |
29 | def decide(self, env):
30 | return Actions.move4(), EmptyArgs
31 |
32 | #Adds basic agressive behavior
33 | class PassiveAgressive(NPC):
34 | def __init__(self, pos, rageTime=5):
35 | super().__init__(pos)
36 | self.rageClock = AI.RageClock(0)
37 | self.rageTime = rageTime
38 |
39 | def decide(self, world):
40 | if not self.rageClock.isActive():
41 | return Actions.move4(), EmptyArgs
42 |
43 | self.rageClock.tick()
44 | action = AI.searchAndDestroy, (world,
45 | self.pos, Enums.Entity.NEURAL)
46 | return action, []
47 |
48 | def registerHit(self, attacker, dmg):
49 | super(PassiveAgressive, self).registerHit(attacker, dmg)
50 | self.rageClock = AI.RageClock(self.rageTime)
51 |
52 |
53 |
--------------------------------------------------------------------------------
/forge/blade/hook/__init__.py:
--------------------------------------------------------------------------------
1 | from .modules import modules
2 |
--------------------------------------------------------------------------------
/forge/blade/hook/item.py:
--------------------------------------------------------------------------------
1 | #Iterates through all items and hooks them to their respective skills
2 | from forge.blade.item import item
3 | from forge.blade.lib import utils
4 |
5 | #Filled in at runtime with items
6 | class ItemList:
7 | items = []
8 |
9 | def hook():
10 | cls = item.Item
11 | for e in utils.terminalClasses(cls):
12 | skill = e.createSkill
13 | if skill is not None:
14 | if type(skill.skillItems) != list:
15 | skill.skillItems = []
16 | skill.skillItems += [e]
17 | ItemList.items += [e]
18 |
--------------------------------------------------------------------------------
/forge/blade/hook/modules.py:
--------------------------------------------------------------------------------
1 | from os.path import dirname, basename, isfile
2 | import glob
3 | def modules(f):
4 | modules = glob.glob(dirname(f)+"/*.py")
5 | return [ basename(f)[:-3] for f in modules
6 | if isfile(f) and not f.endswith('__init__.py')]
7 |
8 |
9 |
--------------------------------------------------------------------------------
/forge/blade/item/__init__.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/forge/blade/item/armor.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from forge.blade import systems
3 | from forge.blade.systems import skill
4 | from forge.blade.item import item, ore
5 |
6 | class Armor(item.Item):
7 | createSkill = skill.Smithing
8 | useSkill = skill.Defense
9 | alwaysSucceeds = True
10 | oreReq = 4
11 | defense = 0
12 |
13 | class Base(Armor):
14 | useLevel = 1
15 | defense = 0
16 |
17 | class Copper(Armor):
18 | createLevel = 1
19 | useLevel = 1
20 | exp = 40
21 | recipe = systems.Recipe(ore.Copper, Armor.oreReq)
22 | defense = 55
23 |
24 | class Tin(Armor):
25 | createLevel = 5
26 | useLevel = 5
27 | exp = 80
28 | recipe = systems.Recipe(ore.Tin, Armor.oreReq)
29 | defense = 90
30 |
31 | class Iron(Armor):
32 | createLevel = 10
33 | useLevel = 10
34 | exp = 120
35 | recipe = systems.Recipe(ore.Iron, Armor.oreReq)
36 | defense = 105
37 |
38 |
--------------------------------------------------------------------------------
/forge/blade/item/food.py:
--------------------------------------------------------------------------------
1 | from forge.blade.systems import Skill
2 | from forge.blade.item import Item
3 |
4 | class Food(Item.Item):
5 | createSkill = Skill.Cooking
6 | useSkill = Skill.Constitution
7 | heal = None
8 |
9 | class Ration(Food):
10 | useLevel = 1
11 | exp = 0
12 | heal = 1
13 |
14 | class Shrimp(Food):
15 | createLevel = 1
16 | useLevel = 1
17 | exp = 10
18 | heal = 2
19 |
20 | class Sardine(Food):
21 | createLevel = 5
22 | useLevel = 5
23 | exp = 20
24 | heal = 3
25 |
26 | class Herring(Food):
27 | createLevel = 10
28 | useLevel = 10
29 | exp = 30
30 | heal = 5
31 |
32 | class Chicken(Food):
33 | createLevel = 1
34 | useLevel = 1
35 | exp = 10
36 | heal = 3
37 |
38 | class Goblin(Food):
39 | createLevel = 1
40 | useLevel = 5
41 | exp = 10
42 | heal = 5
43 |
--------------------------------------------------------------------------------
/forge/blade/item/item.py:
--------------------------------------------------------------------------------
1 | from forge.blade.systems import skill
2 |
3 | class Item:
4 | createSkill = None
5 | useSkill = None
6 |
7 | createLevel = None
8 | useLevel = None
9 |
10 | exp = 0
11 | amtMade = 1
12 | alwaysSucceeds = True
13 | recipe = None
14 |
15 | class Tool(Item): pass
16 |
17 | class Weapon(Item):
18 | alwaysSucceeds = True
19 | createSkill = skill.Smithing
20 |
21 | #Used as a stand in when no weapon is present
22 | class Base(Weapon):
23 | useLevel = 1
24 | attack = 0
25 | strength = 0
26 | ammo = None
27 |
28 | class Gold(Item):
29 | pass
30 |
31 | class Hammer(Tool): pass
32 | class Tinderbox(Tool): pass
33 | class Pickaxe(Tool): pass
34 | class Rod(Tool): pass
35 |
--------------------------------------------------------------------------------
/forge/blade/item/knife.py:
--------------------------------------------------------------------------------
1 | from forge.blade import systems
2 | from forge.blade.systems import skill
3 | from forge.blade.item import item, ore
4 |
5 | class Knife(item.Weapon):
6 | createSkill = skill.Smithing
7 | useSkill = skill.Ranged
8 | amtMade = 10
9 | oreReq = 1
10 |
11 | class Copper(Knife):
12 | createLevel = 1
13 | useLevel = 1
14 | exp = 10
15 | attack = 5
16 | strength = 4
17 | recipe = systems.Recipe(ore.Copper, Knife.oreReq, amtMade=Knife.amtMade)
18 |
19 | class Tin(Knife):
20 | createLevel = 5
21 | useLevel = 5
22 | exp = 20
23 | recipe = systems.Recipe(ore.Tin, Knife.oreReq, amtMade=Knife.amtMade)
24 | attack = 8
25 | strength = 7
26 |
27 | class Iron(Knife):
28 | createLevel = 10
29 | useLevel = 10
30 | exp = 30
31 | recipe = systems.Recipe(ore.Iron, Knife.oreReq, amtMade=Knife.amtMade)
32 | attack = 10
33 | strength = 8
34 |
--------------------------------------------------------------------------------
/forge/blade/item/ore.py:
--------------------------------------------------------------------------------
1 | from forge.blade.systems import skill
2 | from forge.blade.item import item
3 |
4 | class Ore(item.Item):
5 | createSkill = skill.Mining
6 | useSkill = skill.Smithing
7 |
8 | class Copper(Ore):
9 | createLevel = 1
10 | useLevel = 1
11 | exp = 10
12 | class Tin(Ore):
13 | createLevel = 5
14 | useLevel = 5
15 | exp = 20
16 |
17 | class Iron(Ore):
18 | createLevel = 10
19 | useLevel = 10
20 | exp = 30
21 |
22 |
23 |
--------------------------------------------------------------------------------
/forge/blade/item/rawfish.py:
--------------------------------------------------------------------------------
1 | from forge.blade.systems import skill
2 | from forge.blade.item import item
3 |
4 | class RawFish(item.Item):
5 | createSkill = skill.Fishing
6 | useSkill = skill.Cooking
7 | alwaysSucceeds = False
8 |
9 | class Shrimp(RawFish):
10 | createLevel = 1
11 | useLevel = 1
12 | exp = 10
13 |
14 | class Sardine(RawFish):
15 | createLevel = 5
16 | useLevel = 5
17 | exp = 20
18 |
19 | class Herring(RawFish):
20 | createLevel = 10
21 | useLevel = 10
22 | exp = 30
23 |
24 |
25 |
--------------------------------------------------------------------------------
/forge/blade/item/rawmeat.py:
--------------------------------------------------------------------------------
1 | from forge.blade.systems import Skill
2 | from forge.blade.item import Item
3 |
4 | class RawMeat(Item.Item):
5 | useSkill = Skill.Cooking
6 | alwaysSucceeds = False
7 |
8 | class Chicken(RawMeat):
9 | useLevel = 1
10 | exp = 20
11 |
12 | class Goblin(RawMeat):
13 | useLevel = 5
14 | exp = 40
15 |
16 |
--------------------------------------------------------------------------------
/forge/blade/item/sword.py:
--------------------------------------------------------------------------------
1 | from forge.blade.systems.Recipe import Recipe
2 | from forge.blade.systems import Skill
3 | from forge.blade.item import Item, Ore
4 |
5 |
6 | class Sword(Item.Weapon):
7 | createSkill = Skill.Smithing
8 | useSkill = Skill.Melee
9 | oreReq = 2
10 |
11 | class Copper(Sword):
12 | createLevel = 1
13 | useLevel = 1
14 | exp = 10
15 | recipe = Recipe(Ore.Copper, Sword.oreReq)
16 | attack = 10
17 | strength = 9
18 |
19 | class Tin(Sword):
20 | createLevel = 5
21 | useLevel = 5
22 | exp = 20
23 | recipe = Recipe(Ore.Tin, Sword.oreReq)
24 | attack = 15
25 | strength = 14
26 |
27 | class Iron(Sword):
28 | createLevel = 10
29 | useLevel = 10
30 | exp = 30
31 | recipe = Recipe(Ore.Iron, Sword.oreReq)
32 | attack = 19
33 | strength = 14
34 |
35 |
--------------------------------------------------------------------------------
/forge/blade/item/tool.py:
--------------------------------------------------------------------------------
1 | from forge.blade.item import Item
2 |
3 | class Tool(Item.Item): pass
4 |
--------------------------------------------------------------------------------
/forge/blade/lib/__init__.py:
--------------------------------------------------------------------------------
1 | from .multiset import MultiSet
2 | from .priorityqueue import PriorityQueue
3 | from .stattrak import StatTraker
4 | from .ray import init
5 | from .ray import clearbuffers
6 |
--------------------------------------------------------------------------------
/forge/blade/lib/comms.py:
--------------------------------------------------------------------------------
1 | from forge.blade.action import action, v2
2 |
3 | def isInt(x):
4 | return type(x) in (float, int) and int(x) == x
5 |
6 | class CommChannel:
7 | def __init__(self):
8 | self.outbox = []
9 | self.inbox = []
10 |
11 | def put(self, update):
12 | if len(update) > 0:
13 | self.outbox.append(update)
14 |
15 | def get(self):
16 | inbox = self.inbox
17 | self.inbox = []
18 | return inbox
19 |
20 | def send(self):
21 | outbox = self.outbox
22 | self.outbox = []
23 | return outbox
24 |
25 | def recv(self, updates):
26 | self.inbox += updates
27 |
--------------------------------------------------------------------------------
/forge/blade/lib/multiset.py:
--------------------------------------------------------------------------------
1 | from collections import defaultdict
2 |
3 | class MultiSet:
4 | def __init__(self, capacity=0):
5 | self.data = defaultdict(int)
6 | self.count = 0
7 | self.capacity = capacity
8 |
9 | def __iter__(self):
10 | return self.data.__iter__()
11 |
12 | def countItem(self, item):
13 | return self.data[item]
14 |
15 | @property
16 | def full(self):
17 | return self.capacity != 0 and self.count >= self.capacity
18 |
19 | @property
20 | def empty(self):
21 | return self.count == 0
22 |
23 | def get(self, item):
24 | return self.data[item]
25 |
26 | def isIn(self, item, num=1):
27 | return self.data[item] > num
28 |
29 | def add(self, item, num=1):
30 | assert self.capacity == 0 or self.count+num <= self.capacity
31 | self.data[item] += num
32 | self.count += num
33 |
34 | #Alias
35 | def remove(self, item, num=1):
36 | self.pop(item, num)
37 |
38 | def pop(self, item, num=1):
39 | assert self.capacity == 0 or self.count-num >= 0
40 | self.data[item] -= num
41 | self.count -= num
42 |
43 | def union(self, other):
44 | for e in other:
45 | self.add(e, other.count(e))
46 |
47 | def diff(self, other):
48 | for e in other:
49 | self.remove(e, other.count(e))
50 |
51 | def contains(self, other):
52 | for e in other:
53 | if not isIn(e, other[e]):
54 | return False
55 | return True
56 |
57 |
--------------------------------------------------------------------------------
/forge/blade/lib/priorityqueue.py:
--------------------------------------------------------------------------------
1 | import heapq, itertools
2 | import itertools
3 |
4 | class PriorityQueue:
5 | def __init__(self, capacity, unique=False):
6 | self.q, self.items = [], set()
7 | self.capacity = capacity
8 | self.count = itertools.count()
9 | self.unique = unique
10 |
11 | def get(self, ind):
12 | priority, item = self.tolist()[ind]
13 | return priority, item
14 |
15 | def push(self, item, priority, uniqueKey=None):
16 | if self.unique:
17 | self.items.add(uniqueKey)
18 | count = next(self.count)
19 | if len(self.q) >= self.capacity:
20 | return heapq.heappushpop(self.q, (priority, count, item))
21 | heapq.heappush(self.q, (priority, count, item))
22 |
23 | def pop(self):
24 | priority, _, item = heapq.heappop(self.q)
25 | if self.unique:
26 | self.items.remove(item)
27 | return priority, item
28 |
29 | @property
30 | def peek(self):
31 | return self.peekPriority, self.peekValue
32 |
33 | @property
34 | def peekPriority(self):
35 | ret = heapq.nlargest(1, self.q)
36 | if len(ret) > 0:
37 | return ret[0][0]
38 |
39 | @property
40 | def peekValue(self):
41 | ret = heapq.nlargest(1, self.q)
42 | if len(ret) > 0:
43 | return ret[0][2]
44 |
45 |
46 | def tolist(self):
47 | q = heapq.nlargest(self.n, self.q)
48 | return [(e[0], e[2]) for e in q]
49 |
50 | def priorities(self):
51 | return sorted([e[0] for e in self.q], reverse=True)
52 |
53 | def print(self):
54 | q = heapq.nlargest(self.n, self.q)
55 | print([(e[0]) for e in q], end='')
56 | print()
57 |
58 | @property
59 | def n(self):
60 | return len(self.q)
61 |
62 |
--------------------------------------------------------------------------------
/forge/blade/lib/stattrak.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | import numpy as np
4 | from queue import PriorityQueue
5 | from forge.blade.systems import combat
6 |
7 | class ExchangeEntry:
8 | def __init__(self, item, numBuy, numSell, maxBuyPrice, maxSellPrice):
9 | self.item = item
10 | self.numBuy = numBuy
11 | self.numSell = numSell
12 | self.maxBuyPrice = maxBuyPrice
13 | self.maxSellPrice = maxSellPrice
14 |
15 | #Hackey str get. Only for printing
16 | @property
17 | def itemName(self):
18 | return str(self.item)[17:-2]
19 |
20 | @property
21 | def worth(self):
22 | return (self.numBuy + self.numSell)*self.maxBuyPrice
23 |
24 | def __lt__(self, other):
25 | return True
26 |
27 | def __eq__(self, other):
28 | return False
29 |
30 | class StatTraker:
31 | def __init__(self, maxLen=2048):
32 | self.lenTrak = deque(maxlen=maxLen)
33 |
34 | def update(self, pcs, npcs, exchange):
35 | self.pcs = pcs
36 | self.npcs = npcs
37 |
38 | self.lenTrak.append(len(pcs))
39 | #Update exchange
40 | self.updateExchange(exchange)
41 |
42 | def updateExchange(self, exchange):
43 | self.exchange = PriorityQueue()
44 | buyOffers = exchange.buyOffers
45 | sellOffers = exchange.sellOffers
46 | buyKeys, sellKeys = buyOffers.keys(), sellOffers.keys()
47 | exchangeKeys = list(set(list(buyKeys) + list(sellKeys)))
48 |
49 | for key in exchangeKeys:
50 | keyBuys, keySells = buyOffers[key], sellOffers[key]
51 | topBuy = keyBuys.peek()
52 | topSell = keySells.peek()
53 |
54 | if topBuy is not None:
55 | numBuy, maxBuyPrice = topBuy.quantLeft, topBuy.itemPrice
56 | item = topBuy.item
57 | else:
58 | numBuy, maxBuyPrice = 0, 0
59 |
60 | if topSell is not None:
61 | numSell, minSellPrice = topSell.quantLeft, topSell.itemPrice
62 | item = topSell.item
63 | else:
64 | numSell, minSellPrice = 0, 0
65 |
66 | #Compute total buy value
67 | totalBuy = 0
68 | for e in keyBuys.queue:
69 | totalBuy += e.coffer
70 |
71 | entry = ExchangeEntry(item, numBuy, numSell,
72 | maxBuyPrice, minSellPrice)
73 |
74 | self.exchange.put(entry, totalBuy)
75 |
76 | @property
77 | def numEntities(self):
78 | return np.asarray(list(self.lenTrak))
79 |
80 | class StatBlock:
81 | def __init__(self, entity):
82 | self.timeAlive = entity.timeAlive
83 | self.level = combat.combatLevel(entity.skills)
84 | self.defense = entity.skills.defense.level
85 | self.melee = entity.skills.melee.level
86 | self.ranged = entity.skills.ranged.level
87 |
88 |
89 |
--------------------------------------------------------------------------------
/forge/blade/systems/__init__.py:
--------------------------------------------------------------------------------
1 | from .droptable import DropTable
2 | from .exchange import Exchange
3 | from .recipe import Recipe
4 | from .inventory import Inventory
5 | from .skill import Skill
6 |
--------------------------------------------------------------------------------
/forge/blade/systems/combat.py:
--------------------------------------------------------------------------------
1 | #Various utilities for managing combat, including hit/damage
2 |
3 | import numpy as np
4 |
5 | def combatLevel(skills):
6 | hp = skills.constitution.level
7 | defense = skills.defense.level
8 | melee = skills.melee.level
9 | ranged = skills.ranged.level
10 |
11 | base = 0.25*(defense + hp)
12 | meleeAdjust = 0.65*melee
13 | rangeAdjust = 0.325*(np.floor(ranged/2)+ranged)
14 | final = np.floor(base + max(meleeAdjust, rangeAdjust))
15 | return final
16 |
17 | def attack(entity, targ, skill):
18 | attackLevel = skill.level
19 | defenseLevel = targ.skills.defense.level
20 |
21 | attackBonus, strengthBonus = 0, 0
22 | if entity.isPC:
23 | if skill.isMelee:
24 | equip = entity.equipment.melee
25 | elif skill.isRanged:
26 | equip = entity.equipment.ranged
27 | if equip.ammo is not None and equip.ammo <= 0:
28 | return
29 | attackBonus, strengthBonus = equip.attack, equip.strength
30 |
31 | defenseBonus = 0
32 | if targ.isPC:
33 | defenseBonus = targ.equipment.armor.defense
34 |
35 | dmg = 0
36 | if isHit(attackLevel, attackBonus, defenseLevel, defenseBonus):
37 | dmg = damage(attackLevel, strengthBonus)
38 |
39 | if entity.isPC:
40 | entity.skills.addCombatExp(skill, dmg)
41 | if entity.isPC:
42 | targ.skills.addCombatExp(targ.skills.defense, dmg)
43 | targ.registerHit(entity, dmg)
44 |
45 | #Compute maximum damage roll
46 | def maxHit(effectiveLevel, equipmentBonus):
47 | return np.floor(0.5 + (8+effectiveLevel)*(equipmentBonus+64.0)/640.0)
48 |
49 | #Compute maximum attack or defense roll (same formula)
50 | def maxAttackDefense(effectiveLevel, equipmentBonus):
51 | return effectiveLevel*(equipmentBonus+64)
52 |
53 | #Compute hit chance from max attack and defense
54 | def accuracy(atk, dfn):
55 | if atk > dfn:
56 | return 1 - (dfn+2) / (2*(atk+1))
57 | return atk/(2*(dfn+1))
58 |
59 | def isHit(attackLevel, attackBonus, defenseLevel, defenseBonus):
60 | maxAttack = maxAttackDefense(attackLevel, attackBonus)
61 | maxDefense = maxAttackDefense(defenseLevel, defenseBonus)
62 | acc = accuracy(maxAttack, maxDefense)
63 | return np.random.rand() < acc
64 |
65 | def damage(strengthLevel, strengthBonus):
66 | mmax = maxHit(strengthLevel, strengthBonus)
67 | return np.random.randint(1, 1 + mmax)
68 |
69 |
--------------------------------------------------------------------------------
/forge/blade/systems/droptable.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | class Range():
4 | def __init__(self, mmin, mmax):
5 | self.mmin = mmin
6 | self.mmax = mmax
7 |
8 | @property
9 | def value(self):
10 | return np.random.randint(self.mmin, self.mmax+1)
11 |
12 | class Drop:
13 | def __init__(self, item, amount, prob):
14 | self.item = item
15 | self.amount = amount
16 | self.prob = prob
17 |
18 | def roll(self):
19 | if np.random.rand() < self.prob:
20 | if type(self.amount) == int:
21 | return (self.item(), self.amount)
22 | return (self.item(), self.amount.value)
23 |
24 | class DropTable:
25 | def __init__(self):
26 | self.drops = []
27 |
28 | def add(self, item, quant, prob=1.0):
29 | self.drops += [Drop(item, quant, prob)]
30 |
31 | def roll(self):
32 | ret = []
33 | for e in self.drops:
34 | drop = e.roll()
35 | if drop is not None:
36 | ret += [drop]
37 | return ret
38 |
--------------------------------------------------------------------------------
/forge/blade/systems/equipment.py:
--------------------------------------------------------------------------------
1 | from forge.blade.item import item, armor
2 |
3 | class Equipment:
4 | def __init__(self):
5 | self.ammo = 0
6 | self.resetArmor()
7 | self.resetMelee()
8 | self.resetRanged()
9 |
10 | def resetArmor(self):
11 | self.armor = armor.Base()
12 |
13 | def resetMelee(self):
14 | self.melee = item.Base()
15 |
16 | def resetRanged(self):
17 | self.ranged = item.Base()
18 |
19 |
--------------------------------------------------------------------------------
/forge/blade/systems/experience.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | class ExperienceCalculator:
4 | def __init__(self):
5 | self.exp = []
6 | self.tabulateExp()
7 |
8 | def tabulateExp(self, numLevels=99):
9 | for i in range(numLevels):
10 | if i == 0:
11 | self.exp += [0]
12 | else:
13 | increment = np.floor(np.floor(i + 300*(2**(i/7.0)))/4.0)
14 | self.exp += [self.exp[-1] + increment]
15 |
16 | def expAtLevel(self, level):
17 | return self.exp[level]
18 |
19 | def levelAtExp(self, exp):
20 | return np.searchsorted(self.exp, exp)
21 |
--------------------------------------------------------------------------------
/forge/blade/systems/inventory.py:
--------------------------------------------------------------------------------
1 | from forge.blade.item import item, armor
2 |
3 | class Inventory:
4 | def __init__(self):
5 | self.ammo = 0
6 | self.resetArmor()
7 | self.resetMelee()
8 | self.resetRanged()
9 |
10 | def resetArmor(self):
11 | self.armor = Armor.Base()
12 |
13 | def resetMelee(self):
14 | self.melee = Item.Base()
15 |
16 | def resetRanged(self):
17 | self.ranged = Item.Base()
18 |
--------------------------------------------------------------------------------
/forge/blade/systems/recipe.py:
--------------------------------------------------------------------------------
1 | from forge.blade import lib
2 |
3 | class Recipe:
4 | def __init__(self, *args, amtMade=1):
5 | self.amtMade = amtMade
6 | self.blueprint = lib.MultiSet()
7 | for i in range(0, len(args), 2):
8 | inp = args[i]
9 | amt = args[i+1]
10 | self.blueprint.add(inp, amt)
11 |
--------------------------------------------------------------------------------
/forge/blade/systems/skill.py:
--------------------------------------------------------------------------------
1 | import abc
2 |
3 | import numpy as np
4 | from forge.blade.systems import experience
5 |
6 | class Skills:
7 | def __init__(self):
8 | self.melee = Melee()
9 | self.ranged = Ranged()
10 | self.defense = Defense()
11 | self.constitution = Constitution()
12 |
13 | self.fishing = Fishing()
14 | self.mining = Mining()
15 |
16 | self.cooking = Cooking()
17 | self.smithing = Smithing()
18 |
19 | def addCombatExp(self, skill, dmg):
20 | skill.exp += int(3*dmg)
21 | self.constitution.exp += int(dmg)
22 |
23 | class Skill:
24 | skillItems = abc.ABCMeta
25 | expCalculator = experience.ExperienceCalculator()
26 | def __init__(self):
27 | self.exp = 0
28 |
29 | @property
30 | def level(self):
31 | return self.expCalculator.levelAtExp(self.exp)
32 |
33 | class CombatSkill(Skill):
34 | @property
35 | def isMelee(self):
36 | return False
37 |
38 | @property
39 | def isRanged(self):
40 | return False
41 |
42 | class NonCombatSkill(Skill):
43 | def success(self, levelReq):
44 | level = self.level
45 | if level < levelReq:
46 | return False
47 | chance = 0.5 + 0.05*(level - levelReq)
48 | if chance >= 1.0:
49 | return True
50 | return np.random.rand() < chance
51 |
52 | def attempt(self, inv, item):
53 | if (item.createSkill != self.__class__ or
54 | self.level < item.createLevel):
55 | return
56 |
57 | if item.recipe is not None:
58 | #Check that everything is available
59 | if not inv.satisfies(item.recipe): return
60 | inv.removeRecipe(item.recipe)
61 |
62 | if item.alwaysSucceeds or self.success(item.createLevel):
63 | inv.add(item, item.amtMade)
64 | self.exp += item.exp
65 | return True
66 |
67 | class HarvestingSkill(NonCombatSkill):
68 | #Attempt each item from highest to lowest tier until success
69 | def harvest(self, inv):
70 | for e in self.skillItems:
71 | if self.attempt(inv, e):
72 | return
73 |
74 | class ProcessingSkill(NonCombatSkill):
75 | def process(self, inv, item):
76 | self.attempt(inv, item)
77 |
78 | class Fishing(HarvestingSkill): pass
79 |
80 | class Mining(HarvestingSkill): pass
81 |
82 | class Cooking(ProcessingSkill): pass
83 |
84 | class Smithing(ProcessingSkill): pass
85 |
86 | class Melee(CombatSkill):
87 | @property
88 | def isMelee(self):
89 | return True
90 |
91 | class Ranged(CombatSkill):
92 | @property
93 | def isRanged(self):
94 | return True
95 |
96 | class Defense(CombatSkill): pass
97 |
98 | class Constitution(CombatSkill): pass
99 |
100 |
--------------------------------------------------------------------------------
/forge/embyr:
--------------------------------------------------------------------------------
1 | ../../neural-mmo-client/
--------------------------------------------------------------------------------
/forge/ethyr/rollouts.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from itertools import chain
3 | import numpy as np
4 |
5 | from forge.blade.lib.log import Blob
6 |
7 | #Untested function
8 | def discountRewards(rewards, gamma=0.99):
9 | rets, N = [], len(rewards)
10 | discounts = np.array([gamma**i for i in range(N)])
11 | rewards = np.array(rewards)
12 | for idx in range(N): rets.append(sum(rewards[idx:]*discounts[:N-idx]))
13 | return rets
14 |
15 | def sumReturn(rewards):
16 | return [sum(rewards) for e in rewards]
17 |
18 | def mergeRollouts(rollouts):
19 | atnArgs = [rollout.atnArgs for rollout in rollouts]
20 | vals = [rollout.vals for rollout in rollouts]
21 | rets = [rollout.returns for rollout in rollouts]
22 |
23 | atnArgs = list(chain(*atnArgs))
24 | atnArgs = list(zip(*atnArgs))
25 | vals = list(chain(*vals))
26 | rets = list(chain(*rets))
27 |
28 | return atnArgs, vals, rets
29 |
30 | class Rollout:
31 | def __init__(self, returnf=discountRewards):
32 | self.atnArgs = []
33 | self.vals = []
34 | self.rewards = []
35 | self.pop_rewards = []
36 | self.returnf = returnf
37 | self.feather = Feather()
38 |
39 | def step(self, atnArgs, val, reward):
40 | self.atnArgs.append(atnArgs)
41 | self.vals.append(val)
42 | self.rewards.append(reward)
43 |
44 | def finish(self):
45 | self.rewards[-1] = -1
46 | self.returns = self.returnf(self.rewards)
47 | self.lifespan = len(self.rewards)
48 | self.feather.finish()
49 |
50 | #Rollout logger
51 | class Feather:
52 | def __init__(self):
53 | self.expMap = set()
54 | self.blob = Blob()
55 |
56 | def scrawl(self, stim, ent, val, reward):
57 | self.blob.annID = ent.annID
58 | tile = self.tile(stim)
59 | self.move(tile, ent.pos)
60 | #self.action(arguments, atnArgs)
61 | self.stats(val, reward)
62 |
63 | def tile(self, stim):
64 | R, C = stim.shape
65 | rCent, cCent = R//2, C//2
66 | tile = stim[rCent, cCent]
67 | return tile
68 |
69 | def action(self, arguments, atnArgs):
70 | move, attk = arguments
71 | moveArgs, attkArgs, _ = atnArgs
72 | moveLogits, moveIdx = moveArgs
73 | attkLogits, attkIdx = attkArgs
74 |
75 | def move(self, tile, pos):
76 | tile = type(tile.state)
77 | if pos not in self.expMap:
78 | self.expMap.add(pos)
79 | self.blob.unique[tile] += 1
80 | self.blob.counts[tile] += 1
81 |
82 | def stats(self, value, reward):
83 | self.blob.reward.append(reward)
84 | self.blob.value.append(float(value))
85 |
86 | def finish(self):
87 | self.blob.finish()
88 |
89 |
--------------------------------------------------------------------------------
/forge/ethyr/stim.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 |
4 | def center(x, mmax):
5 | return (x - mmax/2.0)/mmax
6 |
7 | def oneHot(v, n):
8 | ary = np.zeros(n)
9 | ary[v] = 1
10 | return ary
11 |
12 | def entity(ent, other, config):
13 | r, c = ent.pos
14 | r = center(r, ent.R)
15 | c = center(c, ent.C)
16 | return stats(ent, other, config)
17 |
18 | def deltaOneHot(pos, stimSz):
19 | n = 2 * stimSz + 1
20 | r, c = pos
21 | r, c = r+stimSz, c+stimSz
22 | r = r * n
23 | idx = int(r + c)
24 | return oneHot(idx, int(n**2))
25 |
26 | def stats(ent, other, config):
27 | health = ent.health.center()
28 | food = ent.food.center()
29 | water = ent.water.center()
30 |
31 | lifetime = center(ent.timeAlive, 100)
32 | damage = ent.damage
33 | if damage is None:
34 | damage = 0
35 | damage = center(damage, 5)
36 | freeze = center(ent.freeze, 2)
37 |
38 | #Cant use one hot colors because it causes dimensional
39 | #conflicts when new pops are added at test time
40 | sameColor = float(ent.colorInd == other.colorInd) - 0.5
41 |
42 | rSelf, cSelf = ent.pos
43 | r, c = center(rSelf, ent.R), center(cSelf, ent.C)
44 |
45 | rOther, cOther = other.pos
46 | rDelta, cDelta = rOther - rSelf, cOther - cSelf
47 | ret = np.array([lifetime, health, food, water,
48 | r, c, rDelta, cDelta, damage, sameColor, freeze])
49 | return ret
50 |
51 | def environment(env, ent, sz, config):
52 | R, C = env.shape
53 | conv, ents = np.zeros((2, R, C)), []
54 | for r in range(R):
55 | for c in range(C):
56 | t, e = tile(ent, env[r, c], sz, config)
57 | conv[:, r, c] = t
58 | ents += e
59 | assert len(ents) > 0
60 | ents = np.array(ents)
61 | return conv, ents
62 |
63 | def tile(ent, t, sz, config):
64 | nTiles = 8
65 | index = t.state.index
66 | assert index >= 0 and index < nTiles
67 | conv = [index, t.nEnts]
68 |
69 | ents = []
70 | r, c = ent.pos
71 | for e in t.ents.values():
72 | statStim = stats(ent, e, config)
73 | e.stim = statStim
74 | ents.append(statStim)
75 |
76 | return conv, ents
77 |
78 |
79 |
--------------------------------------------------------------------------------
/forge/ethyr/torch/__init__.py:
--------------------------------------------------------------------------------
1 | from .stim import Stim
2 |
--------------------------------------------------------------------------------
/forge/ethyr/torch/loss.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 |
4 | import torch
5 | from torch import nn
6 | from torch.nn import functional as F
7 |
8 | def advantage(returns, val):
9 | A = returns - val
10 | adv = (A - A.mean()) / (1e-4 + A.std())
11 | adv = adv.detach()
12 | return adv
13 |
14 | def policyLoss(logProb, atn, adv):
15 | pgLoss = -logProb.gather(1, atn.view(-1, 1))
16 | return (pgLoss * adv).mean()
17 |
18 | def valueLoss(v, returns):
19 | return (0.5 * (v - returns) **2).mean()
20 |
21 | def entropyLoss(prob, logProb):
22 | return (prob * logProb).sum(1).mean()
23 |
24 | def pad(seq):
25 | seq = [e.view(-1) for e in seq]
26 | lens = [(len(e), idx) for idx, e in enumerate(seq)]
27 | lens, idx = zip(*sorted(lens, reverse=True))
28 | seq = np.array(seq)[np.array(idx)]
29 |
30 | seq = torch.nn.utils.rnn.pad_sequence(seq, batch_first=True)
31 | #seq = seq.squeeze(dim=1)
32 | idx = torch.tensor(idx).view(-1, 1).expand_as(seq)
33 | seq = seq.gather(0, idx)
34 |
35 | return seq
36 |
37 | def PG(pi, atn, val, returns):
38 | prob = pad([F.softmax(e, dim=1) for e in pi])
39 | logProb = pad([F.log_softmax(e, dim=1) for e in pi])
40 |
41 | adv = advantage(returns, val)
42 | polLoss = policyLoss(logProb, atn, adv)
43 | entLoss = entropyLoss(prob, logProb)
44 | return polLoss, entLoss
45 |
46 | #A bit stale--not currently used because
47 | #Vanilla PG is equivalent with 1 update per minibatch
48 | class PPO(nn.Module):
49 | def forward(self, pi, v, atn, returns):
50 | prob, logProb = F.softmax(pi, dim=1), F.log_softmax(pi, dim=1)
51 | atnProb = prob.gather(1, atn.view(-1, 1))
52 |
53 | #Compute advantage
54 | A = returns - v
55 | adv = (A - A.mean()) / (1e-4 + A.std())
56 | adv = adv.detach()
57 |
58 | #Clipped ratio loss
59 | prob, probOld, logProb = F.softmax(pi, dim=1), F.softmax(piOld, dim=1), F.log_softmax(pi, dim=1)
60 | atnProb, atnProbOld = prob.gather(1, atn), probOld.gather(1, atn)
61 |
62 | ratio = atnProb / (atnProbOld + 1e-6)
63 | surr1 = ratio*adv
64 | surr2 = torch.clamp(ratio, min=1. - self.clip, max=1. + self.clip) * adv
65 | policyLoss = -torch.min(surr1, surr2)
66 |
67 | #Compute value loss
68 | valueLoss = (0.5 * (v - returns) **2).mean()
69 |
70 | #Compute entropy loss
71 | entropyLoss = (prob * logProb).sum(1).mean()
72 |
73 | return policyLoss, valueLoss, entropyLoss
74 |
--------------------------------------------------------------------------------
/forge/ethyr/torch/optim.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | from torch import optim
4 | from torch.autograd import Variable
5 | from pdb import set_trace as T
6 |
7 | from forge.ethyr import rollouts
8 | from forge.ethyr.torch import loss
9 | from forge.ethyr.torch import param
10 |
11 | class ManualAdam(optim.Adam):
12 | def step(self, grads):
13 | grads = Variable(torch.Tensor(np.array(grads)))
14 | self.param_groups[0]['params'][0].grad = grads
15 | super().step()
16 |
17 | class ManualSGD(optim.SGD):
18 | def step(self, grads):
19 | grads = Variable(torch.Tensor(np.array(grads)))
20 | self.param_groups[0]['params'][0].grad = grads
21 | super().step()
22 |
23 | def backward(rolls, anns, valWeight=0.5, entWeight=0):
24 | atns, vals, rets = rollouts.mergeRollouts(rolls.values())
25 | returns = torch.tensor(rets).view(-1, 1).float()
26 | vals = torch.cat(vals)
27 | pg, entropy, attackentropy = 0, 0, 0
28 | for i, atnList in enumerate(atns):
29 | aArg, aArgIdx = list(zip(*atnList))
30 | aArgIdx = torch.stack(aArgIdx)
31 | l, e = loss.PG(aArg, aArgIdx, vals, returns)
32 | pg += l
33 | entropy += e
34 |
35 | valLoss = loss.valueLoss(vals, returns)
36 | totLoss = pg + valWeight*valLoss + entWeight*entropy
37 |
38 | totLoss.backward()
39 | grads = [param.getGrads(ann) for ann in anns]
40 | reward = np.mean(rets)
41 |
42 | return reward, vals.mean(), grads, pg, valLoss, entropy
43 |
44 |
--------------------------------------------------------------------------------
/forge/ethyr/torch/param.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 |
4 | def zeroGrads(ann):
5 | ind = 0
6 | for e in ann.parameters():
7 | if e.grad is None:
8 | continue
9 | shape = e.size()
10 | nParams = np.prod(shape)
11 | e.grad.data *= 0
12 | ind += nParams
13 |
14 | def setParameters(ann, meanVec):
15 | ind = 0
16 | for e in ann.parameters():
17 | shape = e.size()
18 | nParams = np.prod(shape)
19 | e.data = torch.Tensor(np.array(meanVec[ind:ind+nParams]).reshape(*shape))
20 | ind += nParams
21 |
22 | def setGrads(ann, grads):
23 | ind = 0
24 | for e in ann.parameters():
25 | shape = e.size()
26 | nParams = np.prod(shape)
27 | e.grad.data = torch.Tensor(np.array(grads[ind:ind+nParams]).reshape(*shape))
28 | ind += nParams
29 |
30 | def getParameters(ann):
31 | ret = []
32 | for e in ann.parameters():
33 | ret += e.data.view(-1).numpy().tolist()
34 | return ret
35 |
36 | def getGrads(ann):
37 | ret = []
38 | for param, e in ann.named_parameters():
39 | try:
40 | ret += e.grad.data.view(-1).numpy().tolist()
41 | except:
42 | print('Gradient dimension mismatch. This usually means you have either (1) loaded a model with a different architecture or (2) have a layer for which gradients are not available (e.g. not differentiable or more commonly not being used)')
43 | return ret
44 |
45 |
--------------------------------------------------------------------------------
/forge/ethyr/torch/save.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 | import torch
4 | import time
5 | from forge.blade.lib.utils import EDA
6 |
7 | class Resetter:
8 | def __init__(self, resetTol):
9 | self.resetTicks, self.resetTol = 0, resetTol
10 | def step(self, best=False):
11 | if best:
12 | self.resetTicks = 0
13 | elif self.resetTicks < self.resetTol:
14 | self.resetTicks += 1
15 | else:
16 | self.resetTicks = 0
17 | return True
18 | return False
19 |
20 | class Saver:
21 | def __init__(self, nANN, root, savef, bestf, resetTol):
22 | self.bestf, self.savef = bestf, savef,
23 | self.root, self.extn = root, '.pth'
24 | self.nANN = nANN
25 |
26 | self.resetter = Resetter(resetTol)
27 | self.rewardAvg, self.best = EDA(), 0
28 | self.start, self.epoch = time.time(), 0
29 | self.resetTol = resetTol
30 |
31 | def save(self, params, opt, fname):
32 | data = {'param': params,
33 | 'opt' : opt.state_dict(),
34 | 'epoch': self.epoch}
35 | torch.save(data, self.root + fname + self.extn)
36 |
37 | def checkpoint(self, params, opt, reward):
38 | self.save(params, opt, self.savef)
39 | best = reward > self.best
40 | if best:
41 | self.best = reward
42 | self.save(params, opt, self.bestf)
43 |
44 | self.time = time.time() - self.start
45 | self.start = time.time()
46 | self.reward = reward
47 | self.epoch += 1
48 |
49 | if self.epoch % 100 == 0:
50 | self.save(params, opt, 'model'+str(self.epoch))
51 |
52 | return self.resetter.step(best)
53 |
54 | def load(self, opt, param, best=False):
55 | fname = self.bestf if best else self.savef
56 | data = torch.load(self.root + fname + self.extn)
57 | param.data = data['param']
58 | if opt is not None:
59 | opt.load_state_dict(data['opt'])
60 | epoch = data['epoch']
61 | return epoch
62 |
63 | def print(self):
64 | print(
65 | 'Tick: ', self.epoch,
66 | ', Time: ', str(self.time)[:5],
67 | ', Lifetime: ', str(self.reward)[:5],
68 | ', Best: ', str(self.best)[:5])
69 |
70 |
--------------------------------------------------------------------------------
/forge/ethyr/torch/stim.py:
--------------------------------------------------------------------------------
1 | from forge.ethyr.torch import utils as tu
2 | from forge.ethyr import stim
3 |
4 | from pdb import set_trace as T
5 |
6 | class Stim:
7 | def __init__(self, ent, env, config):
8 | sz = config.STIM
9 | flat = stim.entity(ent, ent, config)
10 | conv, ents = stim.environment(env, ent, sz, config)
11 |
12 | self.flat = tu.var(flat)
13 | self.conv = tu.var(conv)
14 | self.ents = tu.var(ents)
15 |
--------------------------------------------------------------------------------
/forge/ethyr/torch/utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | from torch import nn
4 | from torch.autograd import Variable
5 |
6 | #Print model size
7 | def modelSize(net):
8 | params = 0
9 | for e in net.parameters():
10 | params += np.prod(e.size())
11 | params = int(params/1000)
12 | print("Network has ", params, "K params")
13 |
14 | #Same padded (odd k)
15 | def Conv2d(fIn, fOut, k, stride=1):
16 | pad = int((k-1)/2)
17 | return torch.nn.Conv2d(fIn, fOut, k, stride=stride, padding=pad)
18 |
19 | def Pool(k, stride=1, pad=0):
20 | #pad = int((k-1)/2)
21 | return torch.nn.MaxPool2d(k, stride=stride, padding=pad)
22 |
23 | def Relu():
24 | return torch.nn.ReLU()
25 |
26 | class FCRelu(nn.Module):
27 | def __init__(self, xdim, ydim):
28 | super().__init__()
29 | self.fc = torch.nn.Linear(xdim, ydim)
30 | self.relu = Relu()
31 |
32 | def forward(self, x):
33 | x = self.fc(x)
34 | x = self.relu(x)
35 | return x
36 |
37 | class ConvReluPool(nn.Module):
38 | def __init__(self, fIn, fOut, k, stride=1, pool=2):
39 | super().__init__()
40 | self.conv = Conv2d(fIn, fOut, k, stride)
41 | self.relu = Relu()
42 | self.pool = Pool(k)
43 |
44 | def forward(self, x):
45 | x = self.conv(x)
46 | x = self.relu(x)
47 | x = self.pool(x)
48 | return x
49 |
50 | #ModuleList wrapper
51 | def moduleList(module, *args, n=1):
52 | return nn.ModuleList([module(*args) for i in range(n)])
53 |
54 | #Variable wrapper
55 | def var(xNp, volatile=False, cuda=False):
56 | x = Variable(torch.from_numpy(xNp), volatile=volatile).float()
57 | if cuda:
58 | x = x.cuda()
59 | return x
60 |
61 | #Full-network initialization wrapper
62 | def initWeights(net, scheme='orthogonal'):
63 | print('Initializing weights. Warning: may overwrite sensitive bias parameters (e.g. batchnorm)')
64 | for e in net.parameters():
65 | if scheme == 'orthogonal':
66 | if len(e.size()) >= 2:
67 | init.orthogonal(e)
68 | elif scheme == 'normal':
69 | init.normal(e, std=1e-2)
70 | elif scheme == 'xavier':
71 | init.xavier_normal(e)
72 |
73 |
--------------------------------------------------------------------------------
/forge/trinity/__init__.py:
--------------------------------------------------------------------------------
1 | from .trinity import Trinity
2 | from .pantheon import Pantheon
3 | from .god import God
4 | from .sword import Sword
5 | from .ann import ANN
6 |
--------------------------------------------------------------------------------
/forge/trinity/god.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from forge.blade.lib.enums import Palette
3 | import numpy as np
4 |
5 | class God:
6 | def __init__(self, config, args):
7 | self.config, self.args = config, args
8 | self.nEnt, self.nANN = config.NENT, config.NPOP
9 | self.popSz = self.nEnt // self.nANN
10 | self.popCounts = np.zeros(self.nANN)
11 | self.palette = Palette(config.NPOP)
12 | self.entID = 0
13 |
14 | #Returns IDs for spawning
15 | def spawn(self):
16 | entID = str(self.entID)
17 | annID = hash(entID) % self.nANN
18 | self.entID += 1
19 |
20 | assert self.popCounts[annID] <= self.popSz
21 | if self.popCounts[annID] == self.popSz:
22 | return self.spawn()
23 |
24 | self.popCounts[annID] += 1
25 | color = self.palette.color(annID)
26 |
27 | return entID, (annID, color)
28 |
29 | def cull(self, annID):
30 | self.popCounts[annID] -= 1
31 | assert self.popCounts[annID] >= 0
32 |
33 | def send(self):
34 | return
35 |
36 | def recv(self, pantheonUpdates):
37 | return
38 |
39 |
--------------------------------------------------------------------------------
/forge/trinity/sword.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from collections import defaultdict
3 | import numpy as np
4 |
5 | from forge import trinity
6 | from forge.ethyr.torch.param import setParameters, zeroGrads
7 | from forge.ethyr.torch import optim
8 | from forge.ethyr.rollouts import Rollout
9 |
10 | class Sword:
11 | def __init__(self, config, args):
12 | self.config, self.args = config, args
13 | self.nANN, self.h = config.NPOP, config.HIDDEN
14 | self.anns = [trinity.ANN(config)
15 | for i in range(self.nANN)]
16 |
17 | self.init, self.nRollouts = True, 32
18 | self.networksUsed = set()
19 | self.updates, self.rollouts = defaultdict(Rollout), {}
20 | self.ents, self.rewards, self.grads = {}, [], None
21 | self.nGrads = 0
22 |
23 | def backward(self):
24 | ents = self.rollouts.keys()
25 | anns = [self.anns[idx] for idx in self.networksUsed]
26 |
27 | reward, val, grads, pg, valLoss, entropy = optim.backward(
28 | self.rollouts, anns, valWeight=0.25,
29 | entWeight=self.config.ENTROPY)
30 | self.grads = dict((idx, grad) for idx, grad in
31 | zip(self.networksUsed, grads))
32 |
33 | self.blobs = [r.feather.blob for r in self.rollouts.values()]
34 | self.rollouts = {}
35 | self.nGrads = 0
36 | self.networksUsed = set()
37 |
38 | def sendGradUpdate(self):
39 | grads = self.grads
40 | self.grads = None
41 | return grads
42 |
43 | def sendLogUpdate(self):
44 | blobs = self.blobs
45 | self.blobs = []
46 | return blobs
47 |
48 | def sendUpdate(self):
49 | if self.grads is None:
50 | return None, None
51 | return self.sendGradUpdate(), self.sendLogUpdate()
52 |
53 | def recvUpdate(self, update):
54 | for idx, paramVec in enumerate(update):
55 | setParameters(self.anns[idx], paramVec)
56 | zeroGrads(self.anns[idx])
57 |
58 | def collectStep(self, entID, atnArgs, val, reward):
59 | if self.config.TEST:
60 | return
61 | self.updates[entID].step(atnArgs, val, reward)
62 |
63 | def collectRollout(self, entID, ent):
64 | assert entID not in self.rollouts
65 | rollout = self.updates[entID]
66 | rollout.finish()
67 | self.nGrads += rollout.lifespan
68 | self.rollouts[entID] = rollout
69 | del self.updates[entID]
70 |
71 | # assert ent.annID == (hash(entID) % self.nANN)
72 | self.networksUsed.add(ent.annID)
73 |
74 | #Two options: fixed number of gradients or rollouts
75 | #if len(self.rollouts) >= self.nRollouts:
76 | if self.nGrads >= 100*32:
77 | self.backward()
78 |
79 | def decide(self, ent, stim):
80 | reward, entID, annID = 0, ent.entID, ent.annID
81 | action, arguments, atnArgs, val = self.anns[annID](ent, stim)
82 | self.collectStep(entID, atnArgs, val, reward)
83 | self.updates[entID].feather.scrawl(
84 | stim, ent, val, reward)
85 | return action, arguments, float(val)
86 |
--------------------------------------------------------------------------------
/forge/trinity/trinity.py:
--------------------------------------------------------------------------------
1 | class Trinity:
2 | def __init__(self, pantheon, god, sword):
3 | self.pantheon = pantheon
4 | self.god = god
5 | self.sword = sword
6 |
7 | #Cluster/Master logic
8 | class Pantheon:
9 | def __init__(self, args): pass
10 | def step(self, recvs): pass
11 |
12 | #Environment logic
13 | class God:
14 | def __init__(self, args, idx): pass
15 | def spawn(self): pass
16 | def send(self): pass
17 | def recv(self, pantheonUpdates): pass
18 |
19 | #Agent logic
20 | class Sword:
21 | def __init__(self, args): pass
22 | def sendUpdate(self): pass
23 | def recvUpdate(self, update): pass
24 | def collectRollout(self, entID, ent): pass
25 | def decide(self, entID, ent, stim): pass
26 |
27 |
--------------------------------------------------------------------------------
/jsuarez/Baselines.py:
--------------------------------------------------------------------------------
1 | class NaiveRandom():
2 | def __init__(self, cuda=False):
3 | #self.cpu = cpu
4 | self.alive = True
5 | self.timeAlive = 0
6 |
7 | def reproduce(self):
8 | return NaiveRandom()
9 |
10 | def interact(self, pc, stimuli, actions):
11 | self.timeAlive += 1
12 | return self.decide(pc, stimuli, actions)
13 |
14 | def death(self):
15 | self.alive = False
16 |
17 | def decide(self, pc, stimuli, actionTree):
18 | done = False
19 | while not actionTree.isLeaf:
20 | actionTree.randomNode()
21 |
22 | #Note: will pass if no valid args
23 | if type(actionTree.action) == Actions.Reproduce:
24 | self.reproduce()
25 | actionTree.decideArgs([])
26 | else:
27 | actionTree.randomArgs()
28 | if actionTree.args is None:
29 | return actionTree.passActionArgs()
30 |
31 | action, args = actionTree.actionArgPair()
32 | #print(str(action) + ' ' + str(args))
33 | return action, args
34 |
35 | class AlwaysPass():
36 | def __init__(self, cuda=False):
37 | self.alive = True
38 | self.timeAlive = 0
39 |
40 | def reproduce(self):
41 | return self.cpu.reproduce()
42 |
43 | def decide(self, pc, stimuli, actionTree):
44 | self.timeAlive += 1
45 | return Actions.Pass(), []
46 |
47 | def death(self):
48 | self.alive = False
49 |
50 |
--------------------------------------------------------------------------------
/jsuarez/CPUUtils.py:
--------------------------------------------------------------------------------
1 | #Utilities for Neural CPUs to interact with the set of actions.
2 |
3 | from pdb import set_trace as T
4 | from sim.lib import Utils
5 | from sim.modules import Skill
6 | from sim.entity.NPC import NPC
7 | from sim.action import Action
8 |
9 | class ActionStats:
10 | numMoves = 4
11 | numAttacks = 2
12 | numEntities = 1 + len(Utils.terminalClasses(NPC))
13 | numSkills = len(Utils.terminalClasses(Skill.Skill))
14 | numActions = 2 + numSkills
15 |
16 | class ActionSpec:
17 | def __init__(self):
18 | self.prev = None
19 | self.roots = [Action.ActionNode, Action.ActionLeaf]
20 | #self.roots = [Actions.ActionLeaf]
21 |
22 | def edges(self):
23 | ret = []
24 | blacklist = (Action.ActionLeaf, Action.Args)
25 | for root in self.roots:
26 | for e in root.__subclasses__():
27 | if e not in blacklist:
28 | ret += [e]
29 | return ret
30 |
31 | def leaves(self):
32 | return Action.ActionLeaf.__subclasses__()
33 |
34 | class SaveManager():
35 | def __init__(self, root):
36 | self.tl, self.ta, self.vl, self.va = [], [], [], []
37 | self.root = root
38 | self.stateDict = None
39 | self.lock = False
40 |
41 | def update(self, net, tl, ta, vl, va):
42 | nan = np.isnan(sum([t.sum(e) for e in net.state_dict().values()]))
43 | if nan or self.lock:
44 | self.lock = True
45 | print('NaN in update. Locking. Call refresh() to reset')
46 | return
47 |
48 | if self.epoch() == 1 or vl < np.min(self.vl):
49 | self.stateDict = net.state_dict().copy()
50 | t.save(net.state_dict(), self.root+'weights')
51 |
52 | self.tl += [tl]; self.ta += [ta]
53 | self.vl += [vl]; self.va += [va]
54 |
55 | np.save(self.root + 'tl.npy', self.tl)
56 | np.save(self.root + 'ta.npy', self.ta)
57 | np.save(self.root + 'vl.npy', self.vl)
58 | np.save(self.root + 'va.npy', self.va)
59 |
60 | def load(self, net, raw=False):
61 | stateDict = t.load(self.root+'weights')
62 | self.stateDict = stateDict
63 | if not raw:
64 | net.load_state_dict(stateDict)
65 | self.tl = np.load(self.root + 'tl.npy').tolist()
66 | self.ta = np.load(self.root + 'ta.npy').tolist()
67 | self.vl = np.load(self.root + 'vl.npy').tolist()
68 | self.va = np.load(self.root + 'va.npy').tolist()
69 |
70 | def refresh(self, net):
71 | self.lock = False
72 | net.load_state_dict(self.stateDict)
73 |
74 | def epoch(self):
75 | return len(self.tl)+1
76 |
77 |
78 |
--------------------------------------------------------------------------------
/jsuarez/Color256.py:
--------------------------------------------------------------------------------
1 | def makeColor(idx, h=1, s=1, v=1):
2 | r, g, b = colorsys.hsv_to_rgb(h, s, v)
3 | rgbval = tuple(int(255*e) for e in [r, g, b])
4 | hexval = '%02x%02x%02x' % rgbval
5 | return Color(str(idx), hexval)
6 |
7 | class Color256:
8 | def make256():
9 | parh, parv = np.meshgrid(np.linspace(0.075, 1, 16), np.linspace(0.25, 1, 16)[::-1])
10 | parh, parv = parh.T.ravel(), parv.T.ravel()
11 | idxs = np.arange(256)
12 | params = zip(idxs, parh, parv)
13 | colors = [makeColor(idx, h=h, s=1, v=v) for idx, h, v in params]
14 | return colors
15 | colors = make256()
16 |
17 |
--------------------------------------------------------------------------------
/jsuarez/ColorEnts.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 | from scipy.misc import imread, imsave
4 | from matplotlib import pyplot as plt
5 | from forge.blade.lib.enums import makeColor
6 |
7 | fDir = 'resource/Entity/'
8 | fName = 'neural'
9 | extension = '.png'
10 | neural = imread('resource/docs/' + fName + extension)
11 | #neural = np.concatenate((neural, 255+np.zeros((16, 16, 1))), axis=2)
12 |
13 | R, C, three = neural.shape
14 | for r in range(R):
15 | for c in range(C):
16 | if neural[r,c,0] == 214:
17 | neural[r, c, -1] = 0
18 |
19 | inds = [(5, 13), (5, 14), (6, 13), (6, 14),
20 | (9, 9), (9, 10), (10, 9), (10, 10),
21 | (13, 13), (13, 14), (14, 13), (14, 14)]
22 |
23 | parh, parv = np.meshgrid(np.linspace(0.075, 1, 16), np.linspace(0.25, 1, 16)[::-1])
24 | parh, parv = parh.T.ravel(), parv.T.ravel()
25 |
26 | idxs = np.arange(256)
27 | params = zip(idxs, parh, parv)
28 | colors = [makeColor(idx, h=h, s=1, v=v) for idx, h, v in params]
29 | for color in colors:
30 | name, val = color.name, color.value
31 | for r, c in inds:
32 | neural[r, c, :3] = val
33 | f = fDir + fName + name + extension
34 | imsave(f, neural.astype(np.uint8))
35 |
--------------------------------------------------------------------------------
/jsuarez/Curiosity.py:
--------------------------------------------------------------------------------
1 |
2 | class PhiNet(nn.Module):
3 | def __init__(self, xdim, h):
4 | super().__init__()
5 | self.conv1 = Conv2d(8, int(h/2), 3, stride=2)
6 | self.conv2 = Conv2d(int(h/2), h, 3, stride=2)
7 | self.fc1 = torch.nn.Linear(5+4*4*h, h)
8 | self.fc2 = torch.nn.Linear(h, h)
9 |
10 | def forward(self, conv, flat):
11 | x = torch.nn.functional.relu(self.conv1(conv))
12 | x = torch.nn.functional.relu(self.conv2(x))
13 | x = x.view(-1)
14 |
15 | x = torch.cat((x, flat))
16 | x = torch.nn.functional.relu(self.fc1(x))
17 | x = self.fc2(x)
18 |
19 | return x.view(1, -1)
20 |
21 | class ForwardsNet(nn.Module):
22 | def __init__(self, xdim, h, ydim):
23 | super().__init__()
24 | self.loss = torch.nn.MSELoss()
25 |
26 | self.fc1 = torch.nn.Linear(NATN+h, h)
27 | self.fc2 = torch.nn.Linear(h, h)
28 |
29 | def forward(self, atn, phiPrev, phi):
30 | atnHot = torch.zeros(NATN)
31 | atnHot.scatter_(0, atn, 1)
32 | atnHot = atnHot.view(1, -1)
33 |
34 | x = torch.cat((atnHot, phiPrev), 1)
35 | x = torch.nn.functional.relu(self.fc1(x))
36 | x = self.fc2(x)
37 |
38 | #Stop grads on phi
39 | loss = self.loss(x, phi)
40 | return loss
41 |
42 | class BackwardsNet(nn.Module):
43 | def __init__(self, h, ydim):
44 | super().__init__()
45 | self.loss = torch.nn.CrossEntropyLoss()
46 |
47 | self.fc1 = torch.nn.Linear(2*h, h)
48 | self.fc2 = torch.nn.Linear(h, ydim)
49 |
50 | def forward(self, phiPrev, phi, atn):
51 | x = torch.cat((phiPrev, phi), 1)
52 | x = torch.nn.functional.relu(self.fc1(x))
53 | x = self.fc2(x)
54 |
55 | loss = self.loss(x, atn)
56 | return loss
57 |
58 | class CurNet(nn.Module):
59 | def __init__(self, xdim, h, ydim):
60 | super().__init__()
61 | self.phi = PhiNet(xdim, h)
62 | self.forwardsDynamics = ForwardsNet(xdim, h, ydim)
63 | self.backwardsDynamics = BackwardsNet(h, ydim)
64 |
65 | def forward(self, ents, entID, atn, conv, flat):
66 |
67 | conv = conv.view(1, *conv.size())
68 | conv = conv.permute(0, 3, 1, 2)
69 |
70 | if entID in ents:
71 | atn, convPrev, flatPrev = ents[entID]
72 | phiPrev = self.phi(convPrev, flatPrev)
73 | phi = self.phi(conv, flat)
74 |
75 | #Stop both phi's on forward, train both on backward. Confirmed by Harri
76 | fLoss = self.forwardsDynamics(atn, phiPrev.detach(), phi.detach())
77 | bLoss = self.backwardsDynamics(phiPrev, phi, atn)
78 |
79 | ri = fLoss.data[0]
80 |
81 | li = 0.20*fLoss + 0.80*bLoss
82 | else:
83 | ri, li = 0, torch.tensor(0.0)
84 | #ri, li = 0, tu.var(np.zeros(1))
85 |
86 | ents[entID] = (atn, conv, flat)
87 | return ri, li
88 |
--------------------------------------------------------------------------------
/jsuarez/Desciple.py:
--------------------------------------------------------------------------------
1 | class Desciple:
2 | def __init__(self, entID, config, color=None):
3 | self.packet = pc.Packet(entID, config, color)
4 | self.client = pc.Client(self.packet)
5 | self.server = pc.Server(config)
6 | self.sync(self.packet, self.server)
7 | self.sync(self.packet, self.client)
8 |
9 | def sync(self, src, dst):
10 | for attr in self.packet.paramNames():
11 | setattr(dst, attr,
12 | getattr(src, attr))
13 |
14 |
--------------------------------------------------------------------------------
/jsuarez/Handler.py:
--------------------------------------------------------------------------------
1 | #Abstract class. Defines shared routines for managing and updating
2 | #sets of entities within the world. Mainly subclassed by PC/NPC
3 |
4 | from pdb import set_trace as T
5 |
6 | class Handler():
7 | def __init__(self, env, entityType, maxSpawn=None):
8 | self.entities = []
9 | self.initSpawn(env)
10 | self.entityType = entityType
11 | self.maxSpawn = maxSpawn
12 |
13 | def addEntity(self, entity, ent):
14 | self.entities += [entity]
15 | r, c = entity.pos
16 | ent[r, c].append(entity)
17 |
18 | def step(self, world):
19 | for i in range(len(self.entities) - 1, -1, -1):
20 | self.stepAction(world, self.entities[i], i)
21 | self.stepEnv(world.env, self.entities[i])
22 |
23 | def stepEnv(self, env, entity):
24 | pass
25 |
26 | #override
27 | def stepAction(self, world, entity, ind):
28 | pass
29 |
30 | def removeIfDead(self, world, ind):
31 | if not self.entities[ind].isAlive():
32 | self.entities[ind].cpu.death()
33 | r, c = self.entities[ind].pos
34 | world.env.ent[r, c].remove(self.entities[ind])
35 | del self.entities[ind]
36 |
37 | def initSpawn(self, env):
38 | pass
39 |
40 | def spawnPos(self):
41 | pass
42 |
43 | def spawn(self, ent):
44 | if self.maxSpawn is None or len(self.entities) < self.maxSpawn:
45 | pos = self.spawnPos()
46 | entity = self.entityType(pos)
47 | self.addEntity(entity, ent)
48 |
49 |
--------------------------------------------------------------------------------
/jsuarez/MPIUtils.py:
--------------------------------------------------------------------------------
1 | #Author: Joseph Suarez
2 |
3 | from pdb import set_trace as T
4 | import sys, builtins
5 | import numpy as np
6 |
7 | from mpi4py import MPI
8 | from mpi4py.MPI import COMM_WORLD as comm
9 |
10 | MASTER = 0
11 | SILENT = 1
12 | ALL = 2
13 |
14 | class LoadBalancer:
15 | def __init__(self, cores):
16 | self.nCores = len(cores)
17 | self.cores = cores
18 | self.loads = dict((core, 0) for core in cores)
19 |
20 | def assignWorker(self):
21 | #core = 1
22 | #self.loads[core] += 1
23 | #return np.random.choice(self.cores)
24 | #return min([len(e) for e in load.values()])
25 | core = min(self.loads, key=self.loads.get)
26 | self.loads[core] += 1
27 | return core
28 |
29 | def deleteWorker(self, core):
30 | self.loads[core] -= 1
31 |
32 | def print(verbose, *args):
33 | if verbose == ALL or (verbose == MASTER and isMaster()):
34 | builtins.print(*args)
35 | sys.stdout.flush()
36 |
37 | def send(data, dst, seq=None, usePar=False):
38 | if not usePar:
39 | seq.inbox = data
40 | return
41 | comm.send(data, dst)
42 |
43 | def recv(src, seq=None, usePar=False):
44 | if not usePar:
45 | return seq.inbox
46 | return comm.recv(source=src)
47 |
48 | #Returns a req
49 | def isend(data, dst, tag):
50 | return comm.isend(data, dest=dst, tag=tag)
51 |
52 | #Returns a req
53 | def irecv(src, tag):
54 | return comm.irecv(source=src, tag=tag)
55 |
56 | def gather(dst):
57 | return comm.gather(root=dst)
58 |
59 | def assignWorker(clients):
60 | return np.random.choice(clients)
61 |
62 | def distributeFunc(f):
63 | if isMaster():
64 | x = f()
65 | else:
66 | x = None
67 | return distribute(x)
68 |
69 | def npValMean(val):
70 | meanVal = np.zeros_like(val)
71 | comm.Allreduce(val, meanVal, op=MPI.SUM)
72 | return meanVal / comm.Get_size()
73 |
74 | def distribute(x):
75 | return comm.bcast(x, root=MASTER)
76 |
77 | def isMaster():
78 | return comm.Get_rank() == MASTER
79 |
80 | def core():
81 | return comm.Get_rank()
82 |
--------------------------------------------------------------------------------
/jsuarez/NPCHandler.py:
--------------------------------------------------------------------------------
1 | #Defines various handlers for correctly spawning/updating NPCs
2 |
3 | from sim.handler.Handler import Handler
4 | import numpy as np
5 | from pdb import set_trace as T
6 |
7 | class MaterialHandler(Handler):
8 | def __init__(self, env, entityType, material, maxSpawn=None):
9 | self.material= material
10 | super().__init__(env, entityType, maxSpawn=maxSpawn)
11 |
12 | def initSpawn(self, env):
13 | R, C = env.shape
14 | self.spawns = []
15 | for r in range(R):
16 | for c in range(C):
17 | if type(env[r, c].mat) == self.material.value:
18 | self.spawns += [(r, c)]
19 |
20 | def spawnPos(self):
21 | ind = np.random.randint(0, len(self.spawns))
22 | return self.spawns[ind]
23 |
24 | def stepAction(self, world, entity, ind):
25 | ret = self.entities[ind].act(world)
26 |
27 | if not self.entities[ind].isAlive():
28 | self.entities[ind].yieldDrops()
29 | self.removeIfDead(world, ind)
30 | return ret
31 |
--------------------------------------------------------------------------------
/jsuarez/PCHandler.py:
--------------------------------------------------------------------------------
1 | #Handler for PCs. Unlike NPCs, the NPC handler must manage environment
2 | #updates, including food/water levels. Also handles reproduction.
3 |
4 | from pdb import set_trace as T
5 | from collections import defaultdict
6 | from sim.handler.Handler import Handler
7 | from sim.lib import Enums, AI, Actions
8 | from sim.entity.PC import PC
9 | from sim.modules import Skill, ItemHook
10 | from sim.lib.Enums import Material
11 |
12 | class PCHandler(Handler):
13 | def __init__(self, env, cpu):
14 | super().__init__(env, cpu.ann)
15 | self.cpu = cpu
16 |
17 | #Const for now. Better later
18 | def initSpawn(self, env):
19 | self.spawnCent = 13
20 |
21 | def spawnPos(self):
22 | return self.spawnCent, self.spawnCent
23 |
24 | def stepEnv(self, env, entity):
25 | r, c = entity.pos
26 | tile = env.tiles[r, c]
27 | '''
28 | if tile.mat.harvestable:
29 | for drop in env.harvest(r, c):
30 | entity.inv.add(*drop)
31 | '''
32 | #if (type(env.tiles[r, c].mat) in [Material.FOREST.value]):
33 | if (entity.food < entity.maxFood and type(env.tiles[r, c].mat) in [Material.FOREST.value]):
34 | if env.harvest(r, c):
35 | entity.food += 1
36 | if (entity.water < entity.maxWater and
37 | Material.WATER.value in
38 | AI.adjacentMats(env, entity.pos)):
39 | entity.water += 1
40 |
41 | def stepAction(self, world, entity, ind):
42 | actions = Actions.ActionTree(world, entity)
43 | ret = self.entities[ind].act(world, actions)
44 |
45 | self.removeIfDead(world, ind)
46 | '''
47 | if ret not in (-1, None):
48 | pos = AI.randAdjacent(*self.entities[ind].pos)
49 | entity = PC(ret, pos)
50 | self.addEntity(entity, world.ent)
51 | '''
52 |
53 | def spawn(self, ent):
54 | pos = self.spawnPos()
55 | entity = self.cpu.spawn()
56 | entityWrapper = PC(entity, self.spawnPos())
57 | self.addEntity(entityWrapper, ent)
58 |
59 |
60 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/EnvViewport3D.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 | import time
4 | from scipy.misc import imresize, imsave
5 | from enum import Enum
6 |
7 | import pygame
8 | from pygame import Surface
9 |
10 | from forge.embyr import embyr
11 | from forge.embyr import utils as renderutils
12 | from forge.embyr import render
13 | from forge.embyr.texture import TextureInitializer
14 | from forge.blade.lib.enums import Neon, Color256, Defaults
15 | from forge.blade.action.v2 import Attack
16 | from forge.blade.action import action
17 |
18 | from pdb import set_trace as T
19 | import numpy as np
20 |
21 | import os
22 | import kivy3
23 | from kivy.app import App
24 | from kivy3 import Scene, Renderer, PerspectiveCamera
25 | from kivy3.loaders import OBJMTLLoader
26 | from kivy.uix.floatlayout import FloatLayout
27 | from kivy.config import Config
28 | from kivy.graphics import opengl as gl
29 | from kivy.graphics import Mesh as KivyMesh
30 | from kivy3.core.object3d import Object3D
31 | from kivy3.materials import Material
32 | from kivy.core.image import Image
33 | from copy import deepcopy
34 | from forge.embyr.embyr import Application as KivyApp
35 | import pywavefront as pywave
36 | import pytmx
37 | from forge.blade.lib import enums
38 | from forge.embyr.transform import Transform
39 | from forge.embyr import embyr3D
40 |
41 | root = 'forge/embyr/'
42 | Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
43 | shaderf = 'tex/default.glsl'
44 | pi = 3.14159265
45 | NANIM = 4
46 |
47 | class EnvViewport3D(embyr3D.Widget):
48 | def __init__(self, root, realm, **kwargs):
49 | super().__init__(root)
50 | self.root = 'forge/embyr/'
51 | self.rs = embyr3D.RS(root, **kwargs)
52 | self.setupScene()
53 |
54 | def setupScene(self):
55 | self.map = embyr3D.Map(self.rs)
56 |
57 | obj = embyr3D.OBJLoader.load(self.root + 'tex/nn.obj')
58 |
59 | ent = embyr3D.Ent()
60 | ent.pos.x = 40
61 | ent.pos.y = 10
62 | ent.pos.z = 40
63 | self.vecent = ent
64 | self.rs.add(ent)
65 |
66 | ent = embyr3D.Ent()
67 | ent.pos.x = 8
68 | ent.pos.y = 20
69 | ent.pos.z = 8
70 | self.cament = ent
71 | self.rs.add(ent)
72 |
73 | def render(self, dt):
74 | #self.client.render(dt)
75 | #self.step()
76 | x, y, z = self.rs.update(dt)
77 | self.vecent.update_pos(x, 3, z)
78 |
79 | '''
80 | desciples = sorted(self.realm.desciples.items())
81 | if len(desciples) == 0:
82 | return
83 | ent = desciples[0][1]
84 | z, x = 32, 32 #ent.server.pos
85 | self.ent.update_pos(x, self.ent.pos.y, z)
86 | '''
87 |
88 | def refresh(self, trans, iso):
89 | self.iso = iso
90 | mmap = self.map.refresh(trans, self.iso)
91 | ent = self.ent.refresh(trans, self.iso)
92 |
93 | self.blit(mmap, (0, 0))
94 | self.blit(ent, (0, 0))
95 |
96 | self.flip()
97 | return self.surf
98 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/__init__.py:
--------------------------------------------------------------------------------
1 | from .application import Application
2 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/application.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 |
4 | import os
5 | import kivy3
6 | from kivy.app import App
7 | from kivy3 import Scene, Renderer, PerspectiveCamera
8 | from kivy3.loaders import OBJMTLLoader
9 | from kivy.uix.floatlayout import FloatLayout
10 | from kivy.uix.boxlayout import BoxLayout
11 | from kivy.uix.widget import Widget
12 | from kivy.config import Config
13 | from kivy.graphics import opengl as gl
14 | from kivy.graphics import Mesh as KivyMesh
15 | from kivy3.core.object3d import Object3D
16 | from kivy3.materials import Material
17 | from kivy.core.image import Image
18 | from copy import deepcopy
19 | from forge.embyr.embyr import Application as KivyApp
20 | import pywavefront as pywave
21 | import pytmx
22 | from forge.blade.lib import enums
23 | from forge.embyr.transform import Transform
24 | from forge.embyr.client import Client, Canvas
25 | from forge.embyr.EnvViewport3D import EnvViewport3D
26 |
27 | root = 'forge/embyr/'
28 | Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
29 | shaderf = 'tex/default.glsl'
30 | pi = 3.14159265
31 | NANIM = 4
32 |
33 | class Application(KivyApp):
34 | def __init__(self, size, realm, step, conf):
35 | super().__init__(size)
36 | self.W, self.H = size
37 | self.appSize = size
38 | self.root = 'forge/embyr/'
39 | self.title = 'Projekt: Godsword'
40 | self.blocks = dict((mat.value.tex, mat.value)
41 | for mat in enums.Material)
42 |
43 | self.realm = realm
44 | self.step = step
45 | self.conf = conf
46 |
47 | def build(self):
48 | root = FloatLayout()
49 | W, H, side = self.W, self.H, 256
50 | dims = (self.W-side, self.H-side, side)
51 | #self.env1 = EnvViewport3D(root, self.realm, (W, W))
52 | #self.env2 = EnvViewport3D(root, self.realm, (W, W))
53 | canvas = Canvas(self.appSize, root, self.realm, dims, self.conf)
54 | #self.client = Client(canvas, self.appSize, self.realm,
55 | # self.step, dims, NANIM)
56 | self.canvas = canvas
57 |
58 | root.add_widget(canvas)
59 |
60 | #root.add_widget(self.env1)
61 | #root.add_widget(self.env2)
62 |
63 | self.loop(self.update)
64 | return root
65 |
66 | def update(self, dt):
67 | self.step()
68 | #self.env1.render()
69 | #self.env2.render()
70 | self.canvas.render(dt)
71 |
72 | '''
73 | desciples = sorted(self.realm.desciples.items())
74 | if len(desciples) == 0:
75 | return
76 | ent = desciples[0][1]
77 | z, x = 32, 32 #ent.server.pos
78 | self.ent.update_pos(x, self.ent.pos.y, z)
79 | '''
80 |
81 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/block.mtl:
--------------------------------------------------------------------------------
1 | # Blender MTL File: 'block.blend'
2 | # Material Count: 1
3 |
4 | newmtl Material
5 | Ns 96.078431
6 | Ka 1.000000 1.000000 1.000000
7 | Kd 0.640000 0.640000 0.640000
8 | Ks 0.500000 0.500000 0.500000
9 | Ke 0.000000 0.000000 0.000000
10 | Ni 1.000000
11 | d 1.000000
12 | illum 2
13 | map_Kd bg.png
14 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/block.obj:
--------------------------------------------------------------------------------
1 | # Blender v2.79 (sub 0) OBJ File: 'block.blend'
2 | # www.blender.org
3 | mtllib block.mtl
4 | o Cube
5 | v 1.000000 0.000000 -1.000000
6 | v 1.000000 0.000000 0.000000
7 | v -0.000000 0.000000 -0.000000
8 | v 0.000000 0.000000 -1.000000
9 | v 1.000000 1.000000 -1.000000
10 | v 1.000000 1.000000 0.000000
11 | v -0.000000 1.000000 -0.000000
12 | v 0.000000 1.000000 -1.000000
13 | vt 0.000000 0.333333
14 | vt 0.333333 0.333333
15 | vt 0.333333 0.666667
16 | vt 0.000000 0.666667
17 | vt 0.666667 0.000000
18 | vt 0.666667 0.333333
19 | vt 0.333334 0.333333
20 | vt 0.333333 0.000000
21 | vt 0.333333 1.000000
22 | vt 0.000000 1.000000
23 | vt 0.000000 0.666667
24 | vt 0.333333 0.666667
25 | vt 0.333333 0.333334
26 | vt 0.666667 0.333333
27 | vt 0.666667 0.666667
28 | vt 0.333333 0.333333
29 | vt 0.000000 0.333333
30 | vt 0.000000 0.000000
31 | vt 0.333333 0.000000
32 | vt 1.000000 0.000000
33 | vt 1.000000 0.333333
34 | vn 0.0000 -1.0000 0.0000
35 | vn 0.0000 1.0000 0.0000
36 | vn 1.0000 0.0000 0.0000
37 | vn -0.0000 -0.0000 1.0000
38 | vn -1.0000 -0.0000 -0.0000
39 | vn 0.0000 0.0000 -1.0000
40 | usemtl Material
41 | s off
42 | f 1/1/1 2/2/1 3/3/1 4/4/1
43 | f 5/5/2 8/6/2 7/7/2 6/8/2
44 | f 1/9/3 5/10/3 6/11/3 2/12/3
45 | f 2/12/4 6/13/4 7/14/4 3/15/4
46 | f 3/16/5 7/17/5 8/18/5 4/19/5
47 | f 5/5/6 1/20/6 4/21/6 8/6/6
48 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/blocks.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/blocks.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/example1.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2014 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | This example loads simple objects from .obj file and shows how
27 | to use custom shader file
28 | """
29 |
30 | import os
31 | #import kivy3
32 | from kivy.app import App
33 | from kivy3 import Scene, Renderer, PerspectiveCamera
34 | from kivy3.loaders import OBJLoader
35 | from kivy.uix.floatlayout import FloatLayout
36 |
37 |
38 | # Resources pathes
39 | _this_path = os.path.dirname(os.path.realpath(__file__))
40 | shader_file = os.path.join(_this_path, "examples/simple.glsl")
41 | obj_path = os.path.join(_this_path, "examples/testnurbs.obj")
42 |
43 |
44 | class MainApp(App):
45 |
46 | def build(self):
47 | root = FloatLayout()
48 | self.renderer = Renderer(shader_file=shader_file)
49 | scene = Scene()
50 | camera = PerspectiveCamera(15, 1, 1, 1000)
51 | # load obj file
52 | loader = OBJLoader()
53 | obj = loader.load(obj_path)
54 |
55 | scene.add(*obj.children)
56 | for obj in scene.children:
57 | obj.pos.z = -20
58 |
59 | self.renderer.render(scene, camera)
60 | root.add_widget(self.renderer)
61 | self.renderer.bind(size=self._adjust_aspect)
62 | return root
63 |
64 | def _adjust_aspect(self, inst, val):
65 | rsize = self.renderer.size
66 | aspect = rsize[0] / float(rsize[1])
67 | self.renderer.camera.aspect = aspect
68 |
69 |
70 | if __name__ == '__main__':
71 | MainApp().run()
72 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examplecust.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2014 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | Same as example1 but with using default shader file and colorizing
27 | of the objects
28 | """
29 |
30 | import os
31 | #import kivy3
32 | from kivy.app import App
33 | from kivy3 import Scene, Renderer, PerspectiveCamera
34 | from kivy3.loaders import OBJLoader
35 | from kivy.uix.floatlayout import FloatLayout
36 | from pdb import set_trace as T
37 |
38 |
39 | class MainApp(App):
40 |
41 | def build(self):
42 | root = FloatLayout()
43 | self.renderer = Renderer(shader_file='examples/simple.glsl')
44 | scene = Scene()
45 | camera = PerspectiveCamera(30, 1, 1, 1000)
46 | # load obj file
47 | loader = OBJLoader()
48 | obj_path = os.path.join(os.path.dirname(__file__), "cube.obj")
49 | obj = loader.load(obj_path)
50 | cube = obj.children[0]
51 | #scene.add(*obj.children)
52 | #for obj in scene.children:
53 |
54 | scene.add(cube)
55 | cube.pos.z = -20
56 | cube.rot.y = -45
57 | cube.rot.x = 45
58 | cube.material.specular = .35, .35, .35
59 |
60 | # set colors to 3d objects
61 | scene.children[0].material.color = 0., .7, 0. # green
62 | scene.children[0].material.diffuse = 0., .7, 0. # green
63 |
64 | self.renderer.render(scene, camera)
65 | root.add_widget(self.renderer)
66 | self.renderer.bind(size=self._adjust_aspect)
67 | return root
68 |
69 | def _adjust_aspect(self, inst, val):
70 | rsize = self.renderer.size
71 | aspect = rsize[0] / float(rsize[1])
72 | self.renderer.camera.aspect = aspect
73 |
74 |
75 | if __name__ == '__main__':
76 | MainApp().run()
77 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/camera/main.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | import kivy3
4 | from kivy.app import App
5 | from kivy.clock import Clock
6 | from kivy.core.window import Window
7 | from kivy3 import Scene, Renderer, PerspectiveCamera, Vector3
8 | from kivy3.loaders import OBJMTLLoader
9 | from kivy.uix.floatlayout import FloatLayout
10 |
11 | # Resources pathes
12 | _this_path = os.path.dirname(os.path.realpath(__file__))
13 | shader_file = os.path.join(_this_path, "../textures/simple.glsl")
14 | obj_file = os.path.join(_this_path, "../textures/orion.obj")
15 | mtl_file = os.path.join(_this_path, "../textures/orion.mtl")
16 |
17 | class MainApp(App):
18 |
19 | def build(self):
20 | self.look_at = Vector3(0, 0, -1)
21 | root = FloatLayout()
22 | self.renderer = Renderer(shader_file=shader_file)
23 | scene = Scene()
24 | self.camera = PerspectiveCamera(75, 1, 1, 1000)
25 | self.camera.pos.z = 5
26 | loader = OBJMTLLoader()
27 | obj = loader.load(obj_file, mtl_file)
28 | self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
29 | self._keyboard.bind(on_key_down=self._on_keyboard_down)
30 |
31 | scene.add(*obj.children)
32 |
33 | self.renderer.render(scene, self.camera)
34 | self.orion = scene.children[0]
35 |
36 | root.add_widget(self.renderer)
37 | self.renderer.bind(size=self._adjust_aspect)
38 | Clock.schedule_interval(self._rotate_obj, 1 / 20)
39 | return root
40 |
41 | def _adjust_aspect(self, inst, val):
42 | rsize = self.renderer.size
43 | aspect = rsize[0] / float(rsize[1])
44 | self.renderer.camera.aspect = aspect
45 |
46 | def _keyboard_closed(self):
47 | self._keyboard.unbind(on_key_down=self._on_keyboard_down)
48 | self._keyboard = None
49 |
50 | def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
51 | if keycode[1] == 'w':
52 | self.camera.pos.z -= 0.2
53 | elif keycode[1] == 's':
54 | self.camera.pos.z += 0.2
55 | elif keycode[1] == 'a':
56 | self.camera.pos.y -= 0.2
57 | elif keycode[1] == 'd':
58 | self.camera.pos.y += 0.2
59 |
60 | elif keycode[1] == 'up':
61 | self.look_at.y += 0.2
62 | elif keycode[1] == 'down':
63 | self.look_at.y -= 0.2
64 | elif keycode[1] == 'right':
65 | self.look_at.x += 0.2
66 | elif keycode[1] == 'left':
67 | self.look_at.x -= 0.2
68 |
69 | self.camera.look_at(self.look_at)
70 |
71 | def _rotate_obj(self, dt):
72 | self.orion.rot.x += 2
73 | self.orion.rot.z += 2
74 |
75 |
76 | if __name__ == '__main__':
77 | MainApp().run()
78 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/createscene.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | import kivy3
4 | from kivy.app import App
5 | from kivy.uix.floatlayout import FloatLayout
6 | from kivy.clock import Clock
7 | from kivy3 import Mesh, Material
8 | from kivy3 import Scene, Renderer, PerspectiveCamera
9 | from kivy3.extras.geometries import BoxGeometry
10 |
11 |
12 | class SceneApp(App):
13 |
14 | def build(self):
15 | root = FloatLayout()
16 |
17 | self.renderer = Renderer()
18 | self.renderer.set_clear_color((.2, .2, .2, 1.))
19 | scene = Scene()
20 | geometry = BoxGeometry(1, 1, 1)
21 | material = Material(color=(0., 0., 1.), diffuse=(1., 1., 0.),
22 | specular=(.35, .35, .35))
23 | self.cube = Mesh(geometry, material)
24 | self.cube.pos.z = -5
25 | camera = PerspectiveCamera(75, 0.3, 1, 1000)
26 |
27 | scene.add(self.cube)
28 | self.renderer.render(scene, camera)
29 |
30 | root.add_widget(self.renderer)
31 | Clock.schedule_interval(self._rotate_cube, 1 / 20)
32 | self.renderer.bind(size=self._adjust_aspect)
33 |
34 | return root
35 |
36 | def _adjust_aspect(self, inst, val):
37 | rsize = self.renderer.size
38 | aspect = rsize[0] / float(rsize[1])
39 | self.renderer.camera.aspect = aspect
40 |
41 | def _rotate_cube(self, dt):
42 | self.cube.rotation.x += 1
43 | self.cube.rotation.y += 1
44 | self.cube.rotation.z += 1
45 |
46 |
47 | if __name__ == '__main__':
48 | SceneApp().run()
49 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/example1.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2014 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | This example loads simple objects from .obj file and shows how
27 | to use custom shader file
28 | """
29 |
30 | import os
31 | import kivy3
32 | from kivy.app import App
33 | from kivy3 import Scene, Renderer, PerspectiveCamera
34 | from kivy3.loaders import OBJLoader
35 | from kivy.uix.floatlayout import FloatLayout
36 |
37 |
38 | # Resources pathes
39 | _this_path = os.path.dirname(os.path.realpath(__file__))
40 | shader_file = os.path.join(_this_path, "./simple.glsl")
41 | obj_path = os.path.join(_this_path, "./testnurbs.obj")
42 |
43 |
44 | class MainApp(App):
45 |
46 | def build(self):
47 | root = FloatLayout()
48 | self.renderer = Renderer(shader_file=shader_file)
49 | scene = Scene()
50 | camera = PerspectiveCamera(15, 1, 1, 1000)
51 | # load obj file
52 | loader = OBJLoader()
53 | obj = loader.load(obj_path)
54 |
55 | scene.add(*obj.children)
56 | for obj in scene.children:
57 | obj.pos.z = -20
58 |
59 | self.renderer.render(scene, camera)
60 | root.add_widget(self.renderer)
61 | self.renderer.bind(size=self._adjust_aspect)
62 | return root
63 |
64 | def _adjust_aspect(self, inst, val):
65 | rsize = self.renderer.size
66 | aspect = rsize[0] / float(rsize[1])
67 | self.renderer.camera.aspect = aspect
68 |
69 |
70 | if __name__ == '__main__':
71 | MainApp().run()
72 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/example2.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2014 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | Same as example1 but with using default shader file and colorizing
27 | of the objects
28 | """
29 |
30 | import os
31 | import kivy3
32 | from kivy.app import App
33 | from kivy3 import Scene, Renderer, PerspectiveCamera
34 | from kivy3.loaders import OBJLoader
35 | from kivy.uix.floatlayout import FloatLayout
36 |
37 |
38 | class MainApp(App):
39 |
40 | def build(self):
41 | root = FloatLayout()
42 | self.renderer = Renderer()
43 | scene = Scene()
44 | camera = PerspectiveCamera(15, 1, 1, 1000)
45 | # load obj file
46 | loader = OBJLoader()
47 | obj_path = os.path.join(os.path.dirname(__file__), "./testnurbs.obj")
48 | obj = loader.load(obj_path)
49 |
50 | scene.add(*obj.children)
51 | for obj in scene.children:
52 | obj.pos.z = -20
53 | obj.material.specular = .35, .35, .35
54 |
55 | # set colors to 3d objects
56 | scene.children[0].material.color = 0., .7, 0. # green
57 | scene.children[1].material.color = .7, 0., 0. # red
58 | scene.children[2].material.color = 0., 0., .7 # blue
59 | scene.children[3].material.color = .7, .7, 0. # yellow
60 |
61 | scene.children[0].material.diffuse = 0., .7, 0. # green
62 | scene.children[1].material.diffuse = .7, 0., 0. # red
63 | scene.children[2].material.diffuse = 0., 0., .7 # blue
64 | scene.children[3].material.diffuse = .7, .7, 0. # yellow
65 |
66 | self.renderer.render(scene, camera)
67 | root.add_widget(self.renderer)
68 | self.renderer.bind(size=self._adjust_aspect)
69 | return root
70 |
71 | def _adjust_aspect(self, inst, val):
72 | rsize = self.renderer.size
73 | aspect = rsize[0] / float(rsize[1])
74 | self.renderer.camera.aspect = aspect
75 |
76 |
77 | if __name__ == '__main__':
78 | MainApp().run()
79 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/example3.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2014 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | This example loads simple objects from .obj file and shows how
27 | to use custom shader file
28 | """
29 |
30 | import os
31 | import kivy3
32 | from kivy.app import App
33 | from kivy3 import Scene, Renderer, PerspectiveCamera
34 | from kivy3.loaders import OBJMTLLoader
35 | from kivy.uix.floatlayout import FloatLayout
36 |
37 |
38 | class MainApp(App):
39 |
40 | def build(self):
41 | root = FloatLayout()
42 | self.renderer = Renderer()
43 | scene = Scene()
44 | camera = PerspectiveCamera(15, 1, 1, 1000)
45 | # load obj file
46 | loader = OBJMTLLoader()
47 | obj_path = os.path.join(os.path.dirname(__file__), "./testnurbs.obj")
48 | obj = loader.load(obj_path, "./testnurbs.mtl")
49 |
50 | scene.add(*obj.children)
51 | for obj in scene.children:
52 | obj.pos.z = -20
53 |
54 | self.renderer.render(scene, camera)
55 | root.add_widget(self.renderer)
56 | self.renderer.bind(size=self._adjust_aspect)
57 | return root
58 |
59 | def _adjust_aspect(self, inst, val):
60 | rsize = self.renderer.size
61 | aspect = rsize[0] / float(rsize[1])
62 | self.renderer.camera.aspect = aspect
63 |
64 |
65 | if __name__ == '__main__':
66 | MainApp().run()
67 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/monkey.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2014 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | import os
26 | from kivy.app import App
27 | from kivy3 import Scene, Renderer, PerspectiveCamera
28 | from kivy3.loaders import OBJLoader
29 | from kivy.uix.floatlayout import FloatLayout
30 | from kivy.clock import Clock
31 |
32 | # Resources pathes
33 | _this_path = os.path.dirname(os.path.realpath(__file__))
34 | shader_file = os.path.join(_this_path, "./simple.glsl")
35 | obj_file = os.path.join(_this_path, "./monkey.obj")
36 |
37 |
38 | class MainApp(App):
39 |
40 | def build(self):
41 | root = FloatLayout()
42 | self.renderer = Renderer(shader_file=shader_file)
43 | scene = Scene()
44 | # load obj file
45 | loader = OBJLoader()
46 | obj = loader.load(obj_file)
47 | self.monkey = obj.children[0]
48 |
49 | scene.add(*obj.children)
50 | camera = PerspectiveCamera(15, 1, 1, 1000)
51 |
52 | self.renderer.render(scene, camera)
53 | root.add_widget(self.renderer)
54 | Clock.schedule_interval(self._update_obj, 1. / 20)
55 | self.renderer.bind(size=self._adjust_aspect)
56 | return root
57 |
58 | def _update_obj(self, dt):
59 | obj = self.monkey
60 | if obj.pos.z > -30:
61 | obj.pos.z -= 0.5
62 |
63 | def _adjust_aspect(self, inst, val):
64 | rsize = self.renderer.size
65 | aspect = rsize[0] / float(rsize[1])
66 | self.renderer.camera.aspect = aspect
67 |
68 |
69 | if __name__ == '__main__':
70 | MainApp().run()
71 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/textures/main.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | import kivy3
4 | from kivy.app import App
5 | from kivy.clock import Clock
6 | from kivy3 import Scene, Renderer, PerspectiveCamera
7 | from kivy3.loaders import OBJMTLLoader
8 | from kivy.uix.floatlayout import FloatLayout
9 |
10 | # Resources pathes
11 | _this_path = os.path.dirname(os.path.realpath(__file__))
12 | shader_file = os.path.join(_this_path, "./simple.glsl")
13 | obj_file = os.path.join(_this_path, "./orion.obj")
14 | mtl_file = os.path.join(_this_path, "./orion.mtl")
15 |
16 |
17 | class MainApp(App):
18 |
19 | def build(self):
20 | root = FloatLayout()
21 | self.renderer = Renderer(shader_file=shader_file)
22 | scene = Scene()
23 | camera = PerspectiveCamera(15, 1, 1, 1000)
24 | loader = OBJMTLLoader()
25 | obj = loader.load(obj_file, mtl_file)
26 |
27 | scene.add(*obj.children)
28 | for obj in scene.children:
29 | obj.pos.z = -20.
30 |
31 | self.renderer.render(scene, camera)
32 | self.orion = scene.children[0]
33 |
34 | root.add_widget(self.renderer)
35 | self.renderer.bind(size=self._adjust_aspect)
36 | Clock.schedule_interval(self._rotate_obj, 1 / 20)
37 | return root
38 |
39 | def _adjust_aspect(self, inst, val):
40 | rsize = self.renderer.size
41 | aspect = rsize[0] / float(rsize[1])
42 | self.renderer.camera.aspect = aspect
43 |
44 | def _rotate_obj(self, dt):
45 | self.orion.rot.x += 2
46 |
47 |
48 | if __name__ == '__main__':
49 | MainApp().run()
50 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/examples/trackball/main.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | import math
4 | from kivy.app import App
5 | from kivy.clock import Clock
6 | from kivy3 import Scene, Renderer, PerspectiveCamera
7 | from kivy3.loaders import OBJLoader
8 | from kivy.uix.floatlayout import FloatLayout
9 |
10 | # Resources pathes
11 | _this_path = os.path.dirname(os.path.realpath(__file__))
12 | obj_file = os.path.join(_this_path, "./MQ-27.obj")
13 |
14 |
15 | class ObjectTrackball(FloatLayout):
16 |
17 | def __init__(self, camera, radius, *args, **kw):
18 | super(ObjectTrackball, self).__init__(*args, **kw)
19 | self.camera = camera
20 | self.radius = radius
21 | self.phi = 90
22 | self.theta = 0
23 | self._touches = []
24 | self.camera.pos.z = radius
25 | camera.look_at((0, 0, 0))
26 |
27 | def define_rotate_angle(self, touch):
28 | theta_angle = (touch.dx / self.width) * -360
29 | phi_angle = -1 * (touch.dy / self.height) * 360
30 | return phi_angle, theta_angle
31 |
32 | def on_touch_down(self, touch):
33 | touch.grab(self)
34 | self._touches.append(touch)
35 |
36 | def on_touch_up(self, touch):
37 | touch.ungrab(self)
38 | self._touches.remove(touch)
39 |
40 | def on_touch_move(self, touch):
41 | if touch in self._touches and touch.grab_current == self:
42 | if len(self._touches) == 1:
43 | self.do_rotate(touch)
44 | elif len(self._touches) == 2:
45 | pass
46 |
47 | def do_rotate(self, touch):
48 | d_phi, d_theta = self.define_rotate_angle(touch)
49 | self.phi += d_phi
50 | self.theta += d_theta
51 |
52 | _phi = math.radians(self.phi)
53 | _theta = math.radians(self.theta)
54 | z = self.radius * math.cos(_theta) * math.sin(_phi)
55 | x = self.radius * math.sin(_theta) * math.sin(_phi)
56 | y = self.radius * math.cos(_phi)
57 | self.camera.pos = x, y, z
58 |
59 |
60 | class MainApp(App):
61 |
62 | def build(self):
63 | self.renderer = Renderer()
64 | scene = Scene()
65 | camera = PerspectiveCamera(15, 1, 1, 1000)
66 | loader = OBJLoader()
67 | obj = loader.load(obj_file)
68 | self.obj3d = obj
69 | self.camera = camera
70 | root = ObjectTrackball(camera, 1500)
71 |
72 | scene.add(obj)
73 |
74 | self.renderer.render(scene, camera)
75 |
76 | root.add_widget(self.renderer)
77 | self.renderer.bind(size=self._adjust_aspect)
78 | return root
79 |
80 | def _adjust_aspect(self, inst, val):
81 | rsize = self.renderer.size
82 | aspect = rsize[0] / float(rsize[1])
83 | self.renderer.camera.aspect = aspect
84 |
85 |
86 | if __name__ == '__main__':
87 | MainApp().run()
88 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from .scenes.scene import Scene
3 | from .core.object3d import Object3D
4 | from .math.vectors import Vector4, Vector3, Vector2
5 | from .cameras import PerspectiveCamera, OrthographicCamera
6 | from .renderer import Renderer
7 | from .objects.mesh import Mesh
8 | from .materials import Material
9 | from .core.geometry import Geometry
10 | from .core.face3 import Face3
11 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/cameras/__init__.py:
--------------------------------------------------------------------------------
1 | from .orthographic_camera import OrthographicCamera
2 | from .perspective_camera import PerspectiveCamera
3 | from .camera import Camera
4 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/cameras/orthographic_camera.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2013 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | Orthographic camera module
27 | =============
28 |
29 | Implements orthographic camera type.
30 | """
31 |
32 | __all__ = ()
33 |
34 |
35 | class OrthographicCamera():
36 | """ Implements orthographic camera """
37 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/cameras/perspective_camera.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2013 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | Perspective camera module
27 | =============
28 |
29 | Implements perspective camera.
30 | """
31 |
32 | __all__ = ('PerspectiveCamera', )
33 |
34 | from kivy.properties import NumericProperty
35 | from kivy.graphics.transformation import Matrix
36 | from .camera import Camera
37 |
38 |
39 | class PerspectiveCamera(Camera):
40 | """
41 | Implementation of the perspective camera.
42 | """
43 |
44 | aspect = NumericProperty()
45 |
46 | def __init__(self, fov, aspect, near, far, **kw):
47 |
48 | super(PerspectiveCamera, self).__init__(**kw)
49 | self.fov = fov
50 | self.aspect = aspect
51 | self.near = near
52 | self.far = far
53 | self.update_projection_matrix()
54 | self.bind(aspect=self._on_aspect)
55 |
56 | def _on_aspect(self, inst, value):
57 | self.update_projection_matrix()
58 | self.update()
59 |
60 | def update_projection_matrix(self):
61 | m = Matrix()
62 | m.perspective(self.fov * 0.5, self.aspect, self.near, self.far)
63 | self.projection_matrix = m
64 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/core/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/kivy3/core/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/core/face3.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2013 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | Face3 class
27 | =============
28 |
29 | This class should store information about mesh face. Should be used
30 | with some vertices information as it doesn't contain vertices itself,
31 | but only its indices
32 |
33 | """
34 |
35 | from kivy3 import Vector3
36 |
37 |
38 | class Face3(object):
39 |
40 | def __init__(self, a, b, c, normal=None):
41 | self.a = a
42 | self.b = b
43 | self.c = c
44 | self.normal = normal or Vector3(0, 0, 0) # face normal
45 | self.vertex_normals = [] # vertices normals
46 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/core/geometry.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2013 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | """
26 | Geometry class
27 | =============
28 |
29 | """
30 |
31 |
32 | class Geometry(object):
33 |
34 | def __init__(self, name=''):
35 | self.name = name
36 | self.faces = []
37 | self.vertices = []
38 | self.face_vertex_uvs = [[]]
39 |
40 | def compute_vertex_normal(self):
41 | pass
42 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/extras/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/kivy3/extras/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/extras/geometries.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2013 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | from kivy3 import Vector3
26 | from kivy3.core.geometry import Geometry
27 | from kivy3.core.face3 import Face3
28 |
29 |
30 | class BoxGeometry(Geometry):
31 |
32 | _cube_vertices = [(-1, 1, -1), (1, 1, -1),
33 | (1, -1, -1), (-1, -1, -1),
34 | (-1, 1, 1), (1, 1, 1),
35 | (1, -1, 1), (-1, -1, 1),
36 | ]
37 |
38 | _cube_faces = [(0, 1, 2), (0, 2, 3), (3, 2, 6),
39 | (3, 6, 7), (7, 6, 5), (7, 5, 4),
40 | (4, 5, 1), (4, 1, 0), (4, 0, 3),
41 | (7, 4, 3), (5, 1, 2), (6, 5, 2)
42 | ]
43 |
44 | _cube_normals = [(0, 0, 1), (-1, 0, 0), (0, 0, -1),
45 | (1, 0, 0), (0, 1, 0), (0, -1, 0)
46 | ]
47 |
48 | def __init__(self, width, height, depth, **kw):
49 | name = kw.pop('name', '')
50 | super(BoxGeometry, self).__init__(name)
51 | self.width_segment = kw.pop('width_segment', 1)
52 | self.height_segment = kw.pop('height_segment', 1)
53 | self.depth_segment = kw.pop('depth_segment', 1)
54 |
55 | self.w = width
56 | self.h = height
57 | self.d = depth
58 |
59 | self._build_box()
60 |
61 | def _build_box(self):
62 |
63 | for v in self._cube_vertices:
64 | v = Vector3(0.5 * v[0] * self.w,
65 | 0.5 * v[1] * self.h,
66 | 0.5 * v[2] * self.d)
67 | self.vertices.append(v)
68 |
69 | n_idx = 0
70 | for f in self._cube_faces:
71 | face3 = Face3(*f)
72 | normal = self._cube_normals[n_idx / 2]
73 | face3.vertex_normals = [normal, normal, normal]
74 | n_idx += 1
75 | self.faces.append(face3)
76 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/loaders/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from .objloader import OBJLoader, OBJMTLLoader
3 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/materials.py:
--------------------------------------------------------------------------------
1 | """
2 | The MIT License (MIT)
3 |
4 | Copyright (c) 2013 Niko Skrypnik
5 |
6 | Permission is hereby granted, free of charge, to any person obtaining a copy
7 | of this software and associated documentation files (the "Software"), to deal
8 | in the Software without restriction, including without limitation the rights
9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | copies of the Software, and to permit persons to whom the Software is
11 | furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in
14 | all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | THE SOFTWARE.
23 | """
24 |
25 | from kivy.graphics import ChangeState
26 |
27 | # Map for material attributes to shader
28 | # uniform variables
29 | MATERIAL_TO_SHADER_MAP = {
30 | "color": "Ka",
31 | "transparency": "Tr",
32 | "diffuse": "Kd",
33 | "specular": "Ks",
34 | "shininess": "Ns", # specular coefficient
35 | }
36 |
37 |
38 | def set_attribute_to_uniform(attr_name, uniform_var):
39 | MATERIAL_TO_SHADER_MAP[attr_name] = uniform_var
40 |
41 |
42 | class Material(ChangeState):
43 |
44 | def __init__(self, map=None, transparency=1.0, color=(1, 1, 1),
45 | diffuse=(0, 0, 0), specular=(0, 0, 0),
46 | shininess=10.0, **kwargs):
47 | self.map = map
48 | super(Material, self).__init__()
49 | transparency = float(transparency)
50 | color = tuple(float(c) for c in color)
51 | diffuse = tuple(float(d) for d in diffuse)
52 | specular = tuple(float(s) for s in specular)
53 | shininess = float(shininess)
54 |
55 | # set attribute from locals
56 | for k, v in locals().items():
57 | setattr(self, k, v)
58 |
59 | def __setattr__(self, k, v):
60 | if k in MATERIAL_TO_SHADER_MAP:
61 | uniform_var = MATERIAL_TO_SHADER_MAP[k]
62 | self.changes[uniform_var] = v
63 | else:
64 | if type(v) in [float, int, str, list]:
65 | self.changes[k] = v
66 | super(Material, self).__setattr__(k, v)
67 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/math/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/kivy3/math/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/objects/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/kivy3/objects/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/scenes/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/kivy3/scenes/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/kivy3/scenes/scene.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | The MIT License (MIT)
4 |
5 | Copyright (c) 2013 Niko Skrypnik
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in
15 | all copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | THE SOFTWARE.
24 | """
25 |
26 | from kivy.graphics import Callback, UpdateNormalMatrix
27 | from kivy.graphics.opengl import glEnable, glDisable, GL_DEPTH_TEST
28 | from kivy3.core.object3d import Object3D
29 |
30 |
31 | class Scene(Object3D):
32 | """ Scene object """
33 |
34 | def as_instructions(self):
35 | if not self._instructions.children:
36 | for child in self.get_children_instructions():
37 | self._instructions.add(child)
38 | return self._instructions
39 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from setuptools import find_packages, setup
4 | from os.path import join, dirname
5 | from os import walk
6 |
7 | examples = {}
8 | for root, subFolders, files in walk('examples'):
9 | for fn in files:
10 | ext = fn.split('.')[-1].lower()
11 | filename = join(root, fn)
12 | directory = '%s%s' % ('share/kivy3-', dirname(filename))
13 | if directory not in examples:
14 | examples[directory] = []
15 | examples[directory].append(filename)
16 |
17 | setup(
18 | name='kivy3',
19 | version='0.1',
20 | description='Kivy extensions for 3D graphics',
21 | author='Niko Skrypnik',
22 | author_email='nskrypnik@gmail.com',
23 | include_package_data=True,
24 | packages=find_packages(exclude=("tests",)),
25 | data_files=list(examples.items()),
26 | requires=['kivy', ]
27 | )
28 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tests/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/core/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tests/core/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/core/test_object3d.py:
--------------------------------------------------------------------------------
1 |
2 | import unittest
3 | from kivy3 import Object3D
4 | from tests.utils import Sandbox
5 |
6 |
7 | class DummyObject:
8 | pass
9 |
10 |
11 | class Object3DTest(unittest.TestCase):
12 |
13 | def setUp(self):
14 | self.sandbox = Sandbox()
15 | self.obj = Object3D()
16 |
17 | def tearDown(self):
18 | self.sandbox.restore()
19 |
20 | def test_position(self):
21 | obj = self.obj
22 | obj.pos.x = 10
23 | self.assertEqual(obj._position[0], 10)
24 | obj.position.y = 8
25 | self.assertEqual(obj._position[1], 8)
26 | obj.pos.z = 3
27 | self.assertEqual(obj._position[2], 3)
28 |
29 | def test_add_objects(self):
30 | obj = self.obj
31 | self.sandbox.stub(obj, '_add_child')
32 |
33 | obj.add(DummyObject(), DummyObject(), DummyObject())
34 | self.assertEqual(obj._add_child.call_count, 3)
35 |
36 | def test_add_child(self):
37 | obj = self.obj
38 | child = DummyObject()
39 | obj._add_child(child)
40 | self.assertEqual(child.parent, obj)
41 | self.assertEqual(len(obj.children), 1)
42 |
43 |
44 | if __name__ == "__main__":
45 | unittest.main()
46 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/loaders/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tests/loaders/__init__.py
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/loaders/test_loader.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | import unittest
4 | from kivy3.loaders.loader import BaseLoader
5 | from tests.utils import Spy, Sandbox
6 | from kivy.clock import Clock
7 |
8 |
9 | this_dir = os.path.abspath(os.path.dirname(__file__))
10 |
11 |
12 | class BaseLoadertestCase(unittest.TestCase):
13 |
14 | def setUp(self):
15 | self.loader = BaseLoader()
16 | self.sandbox = Sandbox()
17 |
18 | def tearDown(self):
19 | self.sandbox.restore()
20 |
21 | def test_load_when_no_on_load(self):
22 | loader = self.loader
23 | loader.parse = Spy()
24 | loader.load('somefile')
25 | self.assertTrue(loader.parse.is_called())
26 |
27 | def test_on_load_called(self):
28 | loader = self.loader
29 | loader.parse = Spy()
30 | _on_load = Spy()
31 | # mock Clock.schedule_once
32 | self.sandbox.stub(Clock, 'schedule_once', call_fake=lambda x, t: x(0))
33 | loader.load('somesource', on_load=_on_load)
34 | self.assertTrue(_on_load.is_called(), 'on_load callback should be called')
35 |
36 |
37 |
38 | if __name__ == '__main__':
39 | unittest.main()
40 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/loaders/test_objloader.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from kivy3.loaders import OBJLoader
3 |
4 | class OBJLoaderTest(unittest.TestCase):
5 | pass
6 |
7 | if __name__ == '__main__':
8 | unittest.main()
9 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/test_materials.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from utils import Sandbox
3 | from kivy3 import Material
4 |
5 |
6 | class MaterialTest(unittest.TestCase):
7 |
8 | def setUp(self):
9 | self.sandbox = Sandbox()
10 | self.mat = Material()
11 |
12 | def tearDown(self):
13 | self.sandbox.restore()
14 |
15 | def test_setattr(self):
16 | self.mat.color = (0., 0., 0.)
17 | self.assertEquals(self.mat.changes['Ka'], (0., 0., 0.))
18 | self.mat.shininess = 5
19 | self.assertEquals(self.mat.changes['Ns'], 5.)
20 |
21 | if __name__ == '__main__':
22 | unittest.main()
23 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tests/utils.py:
--------------------------------------------------------------------------------
1 | '''
2 | Module provides some test utilities
3 | '''
4 |
5 | class Spy:
6 | '''
7 | This is the test helper which helps us to check whether function has been
8 | called and which parameters have been passed to
9 | '''
10 | def __init__(self, call_fake=None, returns=None):
11 | self.call_count = 0
12 | self.args = []
13 | self.call_fake = call_fake
14 | self.returns = returns
15 |
16 | def __call__(self, *args, **kwargs):
17 | self.args.append((args, kwargs))
18 | self.call_count += 1
19 | if callable(self.call_fake):
20 | return self.call_fake(*args, **kwargs)
21 | else:
22 | if self.returns:
23 | return self.returns
24 |
25 | def is_called(self):
26 | return self.call_count > 0
27 |
28 |
29 | class Sandbox:
30 | '''
31 | This little sucker helps us to mock some modules and functions and then
32 | restore it
33 | '''
34 |
35 | def __init__(self):
36 | 'Constructor'
37 | self._storage = {}
38 |
39 | def stub(self, obj, func_name, **kw):
40 | if not callable(getattr(obj, func_name)):
41 | raise Exception('You may stub only callable objects')
42 | # save previous value of stubbed function
43 | if not obj in self._storage:
44 | obj_storage = {}
45 | self._storage[obj] = obj_storage
46 | else:
47 | obj_storage = self._storage[obj]
48 |
49 | if func_name in obj_storage:
50 | raise Exception('%s function has been already stubbed' % func_name)
51 | # store function into sandbox storage
52 | obj_storage[func_name] = getattr(obj, func_name)
53 |
54 | setattr(obj, func_name, Spy(**kw))
55 |
56 | def restore(self):
57 | if not hasattr(self, '_storage'):
58 | return
59 |
60 | for obj, obj_storage in self._storage.iteritems():
61 | keys_to_del = []
62 | for key, original_value in obj_storage.iteritems():
63 | # restore all original value to an object
64 | setattr(obj, key, original_value)
65 | keys_to_del.append(key)
66 | del self._storage
67 |
68 | def __del__(self):
69 | 'When we destruct object don\'t forget to restore all values'
70 | self.restore()
71 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/black.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/black.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/blinn-phong.glsl:
--------------------------------------------------------------------------------
1 | ---VERTEX SHADER-------------------------------------------------------
2 | #ifdef GL_ES
3 | precision highp float;
4 | #endif
5 |
6 | attribute vec3 v_pos;
7 | attribute vec3 v_normal;
8 | attribute vec4 v_color;
9 | attribute vec2 v_tc0;
10 |
11 | uniform mat4 modelview_mat;
12 | uniform mat4 projection_mat;
13 | uniform float Tr;
14 |
15 | varying vec4 frag_color;
16 | varying vec2 uv_vec;
17 | varying vec4 normal_vec;
18 | varying vec4 vertex_pos;
19 |
20 | void main (void) {
21 | vec4 pos = modelview_mat * vec4(v_pos,1.0);
22 | frag_color = v_color;
23 | uv_vec = v_tc0;
24 | vertex_pos = pos;
25 | normal_vec = vec4(v_normal,0.0);
26 | gl_Position = projection_mat * pos;
27 | }
28 |
29 |
30 | ---FRAGMENT SHADER-----------------------------------------------------
31 | #ifdef GL_ES
32 | precision highp float;
33 | #endif
34 |
35 | varying vec4 normal_vec;
36 | varying vec4 vertex_pos;
37 | varying vec4 frag_color;
38 | varying vec2 uv_vec;
39 |
40 | uniform mat4 normal_mat;
41 | uniform vec3 Kd; // diffuse color
42 | uniform vec3 Ka; // color
43 | uniform vec3 Ks; // specular color
44 | uniform float Tr; // transparency
45 | uniform float Ns; // shininess
46 |
47 |
48 | uniform sampler2D tex;
49 |
50 | void main (void){
51 | vec4 v_normal = normalize( normal_mat * normal_vec );
52 | vec4 v_light = normalize( vec4(0,0,0,1) - vertex_pos );
53 |
54 | vec3 Ia = Ka;
55 | vec3 Id = Kd * max(dot(v_light, v_normal), 0.0);
56 | vec3 Is = Ks * pow(max(dot(v_light, v_normal), 0.0), Ns);
57 |
58 | vec4 tex_color = texture2D(tex, uv_vec);
59 | gl_FragColor = vec4(Ia + Id + Is, Tr);
60 | gl_FragColor = gl_FragColor * tex_color;
61 | }
62 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/default.glsl:
--------------------------------------------------------------------------------
1 | ---VERTEX SHADER-------------------------------------------------------
2 | #ifdef GL_ES
3 | precision highp float;
4 | #endif
5 |
6 | attribute vec3 v_pos;
7 | attribute vec3 v_normal;
8 | attribute vec4 v_color;
9 | attribute vec2 v_tc0;
10 |
11 | uniform mat4 modelview_mat;
12 | uniform mat4 projection_mat;
13 | uniform float Tr;
14 |
15 | varying vec4 frag_color;
16 | varying vec2 uv_vec;
17 | varying vec4 normal_vec;
18 | varying vec4 vertex_pos;
19 |
20 | void main (void) {
21 | vec4 pos = modelview_mat * vec4(v_pos,1.0);
22 | frag_color = v_color;
23 | uv_vec = v_tc0;
24 | vertex_pos = pos;
25 | normal_vec = vec4(v_normal,0.0);
26 | gl_Position = projection_mat * pos;
27 | }
28 |
29 |
30 | ---FRAGMENT SHADER-----------------------------------------------------
31 | #ifdef GL_ES
32 | precision highp float;
33 | #endif
34 |
35 | varying vec4 normal_vec;
36 | varying vec4 vertex_pos;
37 | varying vec4 frag_color;
38 | varying vec2 uv_vec;
39 |
40 | uniform mat4 normal_mat;
41 | uniform vec3 Kd; // diffuse color
42 | uniform vec3 Ka; // color
43 | uniform vec3 Ks; // specular color
44 | uniform float Tr; // transparency
45 | uniform float Ns; // shininess
46 |
47 |
48 | uniform sampler2D tex;
49 |
50 | void main (void){
51 | vec4 v_normal = normalize( normal_mat * normal_vec );
52 | vec4 v_light = normalize( vec4(0,0,0,1) - vertex_pos );
53 |
54 | vec3 Ia = Ka;
55 | vec3 Id = Kd * max(dot(v_light, v_normal), 0.0);
56 | vec3 Is = Ks * pow(max(dot(v_light, v_normal), 0.0), Ns);
57 |
58 | vec4 tex_color = texture2D(tex, uv_vec);
59 | gl_FragColor = vec4(Ia + Id + Is, Tr);
60 | gl_FragColor = gl_FragColor * tex_color;
61 | }
62 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/dirt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/dirt.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/forest.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/forest.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/grass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/grass.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/lava.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/lava.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/nn.mtl:
--------------------------------------------------------------------------------
1 | # Blender MTL File: 'nn.blend'
2 | # Material Count: 2
3 |
4 | newmtl ball
5 | Ns 96.078431
6 | Ka 1.000000 1.000000 1.000000
7 | Kd 1.000000 1.000000 1.000000
8 | Ks 0.500000 0.500000 0.500000
9 | Ke 0.000000 0.000000 0.000000
10 | Ni 1.000000
11 | d 1.000000
12 | illum 2
13 | map_Kd lava.png
14 |
15 | newmtl rod
16 | Ns 96.078431
17 | Ka 1.000000 1.000000 1.000000
18 | Kd 0.000000 0.000000 0.000000
19 | Ks 0.500000 0.500000 0.500000
20 | Ke 0.000000 0.000000 0.000000
21 | Ni 1.000000
22 | d 1.000000
23 | illum 2
24 | map_Kd dirt.png
25 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/simple.glsl:
--------------------------------------------------------------------------------
1 | /* simple.glsl
2 |
3 | simple diffuse lighting based on laberts cosine law; see e.g.:
4 | http://en.wikipedia.org/wiki/Lambertian_reflectance
5 | http://en.wikipedia.org/wiki/Lambert%27s_cosine_law
6 | */
7 | ---VERTEX SHADER-------------------------------------------------------
8 | #ifdef GL_ES
9 | precision highp float;
10 | #endif
11 |
12 | attribute vec3 v_pos;
13 | attribute vec3 v_normal;
14 |
15 | uniform mat4 modelview_mat;
16 | uniform mat4 projection_mat;
17 |
18 | varying vec4 normal_vec;
19 | varying vec4 vertex_pos;
20 |
21 | void main (void) {
22 | //compute vertex position in eye_sapce and normalize normal vector
23 | vec4 pos = modelview_mat * vec4(v_pos,1.0);
24 | vertex_pos = pos;
25 | normal_vec = vec4(v_normal,0.0);
26 | gl_Position = projection_mat * pos;
27 | }
28 |
29 |
30 | ---FRAGMENT SHADER-----------------------------------------------------
31 | #ifdef GL_ES
32 | precision highp float;
33 | #endif
34 |
35 | varying vec4 normal_vec;
36 | varying vec4 vertex_pos;
37 |
38 | uniform mat4 normal_mat;
39 |
40 | void main (void){
41 | //correct normal, and compute light vector (assume light at the eye)
42 | vec4 v_normal = normalize( normal_mat * normal_vec ) ;
43 | vec4 v_light = normalize( vec4(0,0,0,1) - vertex_pos );
44 | //reflectance based on lamberts law of cosine
45 | float theta = clamp(dot(v_normal, v_light), 0.0, 1.0);
46 | gl_FragColor = vec4(theta, theta, theta, 1.0);
47 | }
48 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/stone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/stone.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/water.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/water.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/tex/white.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/extra/embyr_deprecated/embyr/tex/white.png
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/texture.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from forge.embyr import utils as renderutils
3 | from forge.embyr import embyr
4 |
5 | from forge.blade.lib import enums
6 | from forge.blade.lib.enums import Neon
7 |
8 | class TextureInitializer():
9 | def __init__(self, sz, root='resource/', mipLevels=[16, 32, 64, 96, 128], barSz=2):
10 | self.tileSz = sz
11 | self.width = sz
12 | self.barSz = barSz
13 | self.root = root
14 | self.mipLevels = mipLevels
15 |
16 | #self.material = RenderUtils.readRGB(root+'Material/textures.png')
17 | self.material = self.textureTiles(mipLevels)
18 | self.entity = self.textureEnum(enums.Entity,
19 | root+'Entity/', mask=Neon.MASK.rgb)
20 | proj = {
21 | 'melee':renderutils.pgRead(root+'Action/melee.png', mask=Neon.MASK.rgb),
22 | 'range':renderutils.pgRead(root+'Action/range.png', mask=Neon.MASK.rgb),
23 | 'mage':renderutils.pgRead(root+'Action/mage.png', mask=Neon.MASK.rgb),
24 | }
25 | action = {
26 | 'melee':renderutils.pgRead(root+'Action/meleeattack.png', mask=Neon.MASK.rgb),
27 | 'range':renderutils.pgRead(root+'Action/rangeattack.png', mask=Neon.MASK.rgb),
28 | 'mage':renderutils.pgRead(root+'Action/mageattack.png', mask=Neon.MASK.rgb),
29 | }
30 |
31 | self.action = embyr.mips(action, mipLevels)
32 |
33 | #self.action = self.textureEnum(Enums.Entity,
34 | # root+'Action/', mask=Color.MASK)
35 |
36 | def textureTiles(self, mipLevels):
37 | reverse = {}
38 | for mat in enums.Material:
39 | mat = mat.value
40 | texCoords = mat.tex
41 | mat.tex = renderutils.pgRead(self.root + '/tiles/' + mat.tex + '.png')
42 | reverse[mat.index] = mat.tex
43 | return embyr.mips(reverse, self.mipLevels)
44 |
45 | def textureEnum(self, enum, path, mask=None, suffix='.png'):
46 | reverse = {}
47 | for color in enums.Neon.color12():
48 | name = color.name
49 | texPath = path + 'neural' + name + suffix
50 | reverse[name] = renderutils.pgRead(texPath, mask=mask)
51 | for name in range(0, 256):
52 | name = str(name)
53 | texPath = path + 'neural' + name + suffix
54 | reverse[name] = renderutils.pgRead(texPath, mask=mask)
55 | return embyr.mips(reverse, self.mipLevels)
56 |
57 |
58 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr/utils.py:
--------------------------------------------------------------------------------
1 | from scipy.misc import imread
2 | import pygame
3 | import time
4 |
5 | from forge.blade.lib.utils import EDA
6 | from forge.blade.lib.enums import Neon
7 |
8 | def readRGB(path):
9 | return imread(path)[:, :, :3]
10 |
11 | def pgRead(path, mask=None):
12 | try:
13 | img = readRGB(path)
14 | except FileNotFoundError:
15 | return None
16 |
17 | img = pygame.pixelcopy.make_surface(img)
18 | if mask is not None:
19 | img.set_colorkey(mask)
20 |
21 | #For some reason, pygame loads images transformed
22 | img = pygame.transform.flip(img, True, False)
23 | img = pygame.transform.rotate(img, 90)
24 | return img
25 |
26 | class Font:
27 | def render(txt, size, color=Neon.GOLD.rgb):
28 | pass
29 | #return pygame.font.Font('freesansbold.tt', size).render(text, 1, color)
30 |
31 | class Fonts:
32 | def __init__(self, font='freesansbold.ttf'):
33 | sizes=(9, 12, 18, 24, 28, 32, 36)
34 | fonts = [pygame.font.Font(font, sz) for sz in sizes]
35 | self.tiny, self.small, self.normal, self.large, self.Large, self.huge, self.Huge = fonts
36 |
37 | class FPSTracker:
38 | def __init__(self):
39 | self.start = time.time()
40 | self.eda = EDA(k=0.95)
41 | self.fpsVal = 0.0
42 |
43 | def update(self):
44 | tick = time.time() - self.start
45 | self.eda.update(1.0/tick)
46 | self.fpsVal = self.eda.eda
47 | self.start = time.time()
48 |
49 | @property
50 | def fps(self):
51 | return str(self.fpsVal)[:5]
52 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr2d/__init__.py:
--------------------------------------------------------------------------------
1 | from .application import Application
2 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr2d/texture.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from forge.embyr import utils as renderutils
3 | from forge.embyr import embyr
4 |
5 | from forge.blade.lib import enums
6 | from forge.blade.lib.enums import Neon
7 |
8 | class TextureInitializer():
9 | def __init__(self, sz, root='resource/', mipLevels=[16, 32, 64, 96, 128], barSz=2):
10 | self.tileSz = sz
11 | self.width = sz
12 | self.barSz = barSz
13 | self.root = root
14 | self.mipLevels = mipLevels
15 |
16 | #self.material = RenderUtils.readRGB(root+'Material/textures.png')
17 | self.material = self.textureTiles(mipLevels)
18 | self.entity = self.textureEnum(enums.Entity,
19 | root+'Entity/', mask=Neon.MASK.rgb)
20 | proj = {
21 | 'melee':renderutils.pgRead(root+'Action/melee.png', mask=Neon.MASK.rgb),
22 | 'range':renderutils.pgRead(root+'Action/range.png', mask=Neon.MASK.rgb),
23 | 'mage':renderutils.pgRead(root+'Action/mage.png', mask=Neon.MASK.rgb),
24 | }
25 | action = {
26 | 'melee':renderutils.pgRead(root+'Action/meleeattack.png', mask=Neon.MASK.rgb),
27 | 'range':renderutils.pgRead(root+'Action/rangeattack.png', mask=Neon.MASK.rgb),
28 | 'mage':renderutils.pgRead(root+'Action/mageattack.png', mask=Neon.MASK.rgb),
29 | }
30 |
31 | self.action = embyr.mips(action, mipLevels)
32 |
33 | #self.action = self.textureEnum(Enums.Entity,
34 | # root+'Action/', mask=Color.MASK)
35 |
36 | def textureTiles(self, mipLevels):
37 | reverse = {}
38 | for mat in enums.Material:
39 | mat = mat.value
40 | texCoords = mat.tex
41 | mat.tex = renderutils.pgRead(self.root + '/tiles/' + mat.tex + '.png')
42 | reverse[mat.index] = mat.tex
43 | return embyr.mips(reverse, self.mipLevels)
44 |
45 | def textureEnum(self, enum, path, mask=None, suffix='.png'):
46 | reverse = {}
47 | for color in enums.Neon.color12():
48 | name = color.name
49 | texPath = path + 'neural' + name + suffix
50 | reverse[name] = renderutils.pgRead(texPath, mask=mask)
51 | for name in range(0, 256):
52 | name = str(name)
53 | texPath = path + 'neural' + name + suffix
54 | reverse[name] = renderutils.pgRead(texPath, mask=mask)
55 | return embyr.mips(reverse, self.mipLevels)
56 |
57 |
58 |
--------------------------------------------------------------------------------
/jsuarez/extra/embyr_deprecated/embyr2d/utils.py:
--------------------------------------------------------------------------------
1 | from scipy.misc import imread
2 | import pygame
3 | import time
4 |
5 | from forge.blade.lib.utils import EDA
6 | from forge.blade.lib.enums import Neon
7 |
8 | def readRGB(path):
9 | return imread(path)[:, :, :3]
10 |
11 | def pgRead(path, mask=None):
12 | try:
13 | img = readRGB(path)
14 | except FileNotFoundError:
15 | return None
16 |
17 | img = pygame.pixelcopy.make_surface(img)
18 | if mask is not None:
19 | img.set_colorkey(mask)
20 |
21 | #For some reason, pygame loads images transformed
22 | img = pygame.transform.flip(img, True, False)
23 | img = pygame.transform.rotate(img, 90)
24 | return img
25 |
26 | class Font:
27 | def render(txt, size, color=Neon.GOLD.rgb):
28 | pass
29 | #return pygame.font.Font('freesansbold.tt', size).render(text, 1, color)
30 |
31 | class Fonts:
32 | def __init__(self, font='freesansbold.ttf'):
33 | sizes=(9, 12, 18, 24, 28, 32, 36)
34 | fonts = [pygame.font.Font(font, sz) for sz in sizes]
35 | self.tiny, self.small, self.normal, self.large, self.Large, self.huge, self.Huge = fonts
36 |
37 | class FPSTracker:
38 | def __init__(self):
39 | self.start = time.time()
40 | self.eda = EDA(k=0.95)
41 | self.fpsVal = 0.0
42 |
43 | def update(self):
44 | tick = time.time() - self.start
45 | self.eda.update(1.0/tick)
46 | self.fpsVal = self.eda.eda
47 | self.start = time.time()
48 |
49 | @property
50 | def fps(self):
51 | return str(self.fpsVal)[:5]
52 |
--------------------------------------------------------------------------------
/jsuarez/extra/envfig.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from scipy.misc import imread, imresize, imsave
3 | import numpy as np
4 | import imageio
5 |
6 | fracs, imgs = [], []
7 | for i in range(6):
8 | mapPath = 'resource/maps/map' + str(i) + '/map.png'
9 | fractalPath = 'resource/maps/map' + str(i) + '/fractal.png'
10 |
11 | mapImg = imread(mapPath)[256:-256, 256:-256]
12 | fractalImg = imread(fractalPath)[8:-8, 8:-8]
13 | fractalImg = imresize(fractalImg, mapImg.shape)
14 | fractalImg = np.stack(3*[fractalImg], 2)
15 |
16 | fracs.append(fractalImg)
17 | imgs.append(mapImg)
18 |
19 | fracs = np.concatenate(fracs, 1)
20 | imgs = np.concatenate(imgs, 1)
21 | rets = np.concatenate((fracs, imgs), 0)
22 | imsave('envgen.png', rets)
23 |
--------------------------------------------------------------------------------
/jsuarez/extra/envgif.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from scipy.misc import imread, imresize
3 | import numpy as np
4 | import imageio
5 |
6 | frames = []
7 | for i in range(100):
8 | mapPath = 'resource/maps/map' + str(i) + '/map.png'
9 | fractalPath = 'resource/maps/map' + str(i) + '/fractal.png'
10 | print(i)
11 |
12 | mapImg = imread(mapPath)
13 | fractalImg = imread(fractalPath)
14 | fractalImg = imresize(fractalImg, mapImg.shape)
15 | fractalImg = np.stack(3*[fractalImg], 2)
16 |
17 | img = np.concatenate((fractalImg, mapImg), 1)
18 | frames.append(img)
19 |
20 | imageio.mimwrite('envgen.mp4', frames, fps=1.5)
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/jsuarez/extra/makeTourney.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import sys, torch
3 | import os
4 |
5 | expPath = 'resource/data/exps/'
6 | fName = '/bests.pth'
7 |
8 | def loadExp(path):
9 | return torch.load(path)['param']
10 |
11 | def saveExp(dat, path, expName):
12 | if not os.path.exists(path):
13 | os.makedirs(path)
14 | torch.save({'param':dat, 'epoch':0}, path + expName)
15 |
16 | def runMatches():
17 | sz = [8, 32, 64, 128]
18 | n = len(sz)
19 | for prefix in ('nlaw', 'nchaos'):
20 | for i in range(n):
21 | for j in range(i+1, n):
22 | v1, v2 = str(sz[i]), str(sz[j])
23 | runMatch(prefix, v1, v2)
24 |
25 | def runMatch(prefix, v1, v2):
26 | #exp1 = loadExp(expPath + prefix + v1 + fName)
27 | #exp2 = loadExp(expPath + prefix + v2 + fName)
28 |
29 | prefix = 'adam'
30 | exp1 = loadExp(expPath + 'adamentlaw128' + fName)
31 | exp2 = loadExp(expPath + 'adamentchaos128' + fName)
32 |
33 | params = torch.cat((exp1, exp2))
34 | path = expPath + 'tourney_' + prefix + v1 + '_' + v2
35 | saveExp(params, path, fName)
36 |
37 |
38 | #runMatches()
39 | runMatch(None, '128', '128')
40 |
41 |
42 |
--------------------------------------------------------------------------------
/jsuarez/extra/returns.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import experiments
3 | import numpy as np
4 | import logs as loglib
5 | from pdb import set_trace as T
6 |
7 | if __name__ == '__main__':
8 | arg = None
9 | if len(sys.argv) > 1:
10 | arg = sys.argv[1]
11 |
12 | logDir = 'resource/data/exps/'
13 | logName = 'logs.json'
14 | fName = 'frag.png'
15 |
16 | exp = loglib.load(logDir + 'combatscale/' + logName)
17 | rets = []
18 | for idx in range(32):
19 | ret = np.mean(exp['lifespan' + str(idx) + '_mean'][:-50])
20 | rets.append((ret, idx))
21 | rets = sorted(rets)
22 | print(rets)
23 |
24 |
25 |
--------------------------------------------------------------------------------
/jsuarez/log.sh:
--------------------------------------------------------------------------------
1 | #tensorboard --logdir ./resource/logs/
2 | tensorboard --logdir ../results/interactive/gatests/
3 |
4 |
--------------------------------------------------------------------------------
/jsuarez/map/edge.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/edge.png
--------------------------------------------------------------------------------
/jsuarez/map/fullmap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/fullmap.png
--------------------------------------------------------------------------------
/jsuarez/map/largemap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/largemap.png
--------------------------------------------------------------------------------
/jsuarez/map/map.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/map.png
--------------------------------------------------------------------------------
/jsuarez/map/medmap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/medmap.png
--------------------------------------------------------------------------------
/jsuarez/map/medmap.txt:
--------------------------------------------------------------------------------
1 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
3 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
4 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
5 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
6 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
7 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
8 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
9 | 0 2 2 2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 2 2 1 1 1 2 2 2 2 2 2 2 2 0
10 | 0 2 2 2 2 2 2 2 3 3 3 3 3 2 2 2 2 2 2 1 1 4 1 1 2 2 2 2 2 2 2 0
11 | 0 2 2 2 2 2 2 2 3 3 3 3 3 1 1 1 1 1 1 1 4 4 4 1 2 2 2 2 2 2 2 0
12 | 0 2 2 2 2 2 2 2 3 3 3 3 3 1 1 1 1 1 1 1 1 4 1 1 2 2 2 2 2 2 2 0
13 | 0 2 2 2 2 2 2 2 2 3 3 3 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 0
14 | 0 2 2 2 2 2 2 2 2 2 1 1 1 1 1 3 3 1 1 1 1 1 2 2 2 2 2 2 2 2 2 0
15 | 0 2 2 2 2 2 2 2 2 2 1 1 1 1 3 3 3 3 1 1 1 1 2 2 2 2 2 2 2 2 2 0
16 | 0 2 2 2 2 2 2 2 2 2 1 1 1 3 3 3 3 3 3 1 1 1 2 2 2 2 2 2 2 2 2 0
17 | 0 2 2 2 2 2 2 2 2 2 1 1 1 3 3 3 3 3 3 1 1 1 2 2 2 2 2 2 2 2 2 0
18 | 0 2 2 2 2 2 2 2 2 2 1 1 1 1 3 3 3 3 1 1 1 1 2 2 2 2 2 2 2 2 2 0
19 | 0 2 2 2 2 2 2 2 2 2 1 1 1 1 1 3 3 1 1 1 1 4 2 2 2 2 2 2 2 2 2 0
20 | 0 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 4 4 4 2 2 2 2 2 2 2 2 0
21 | 0 2 2 2 2 2 2 2 1 1 4 1 1 1 1 1 1 1 1 4 4 4 4 4 2 2 2 2 2 2 2 0
22 | 0 2 2 2 2 2 2 2 1 4 4 4 1 1 1 1 1 1 4 4 4 4 4 2 2 2 2 2 2 2 2 0
23 | 0 2 2 2 2 2 2 2 1 1 4 1 1 2 2 2 2 2 2 4 4 4 2 2 2 2 2 2 2 2 2 0
24 | 0 2 2 2 2 2 2 2 2 1 1 1 2 2 2 2 2 2 2 2 4 2 2 2 2 2 2 2 2 2 2 0
25 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
26 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
27 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
28 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
29 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
30 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
31 | 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
32 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
33 |
--------------------------------------------------------------------------------
/jsuarez/map/oldfull.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/oldfull.png
--------------------------------------------------------------------------------
/jsuarez/map/profmap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/profmap.png
--------------------------------------------------------------------------------
/jsuarez/map/profs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/profs.png
--------------------------------------------------------------------------------
/jsuarez/map/smallmap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/smallmap.png
--------------------------------------------------------------------------------
/jsuarez/map/smallmap.txt:
--------------------------------------------------------------------------------
1 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 | 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
3 | 0 1 2 2 2 2 2 2 2 2 2 2 2 2 1 0
4 | 0 1 2 2 2 2 2 2 2 2 2 2 2 2 1 0
5 | 0 1 2 2 2 2 2 1 1 2 2 2 2 2 1 0
6 | 0 1 2 2 2 2 1 1 1 1 2 2 2 2 1 0
7 | 0 1 2 2 2 1 1 3 3 1 1 2 2 2 1 0
8 | 0 1 2 2 1 1 3 3 3 3 1 1 2 2 1 0
9 | 0 1 2 2 1 1 3 3 3 3 1 1 2 2 1 0
10 | 0 1 2 2 2 1 1 3 3 1 1 2 2 2 1 0
11 | 0 1 2 2 2 2 1 1 1 1 2 2 2 2 1 0
12 | 0 1 2 2 2 2 2 1 1 2 2 2 2 2 1 0
13 | 0 1 2 2 2 2 2 2 2 2 2 2 2 2 1 0
14 | 0 1 2 2 2 2 2 2 2 2 2 2 2 2 1 0
15 | 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
16 | 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
17 |
--------------------------------------------------------------------------------
/jsuarez/map/testmap.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/map/testmap.txt
--------------------------------------------------------------------------------
/jsuarez/quote.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/quote.txt
--------------------------------------------------------------------------------
/jsuarez/reset.sh:
--------------------------------------------------------------------------------
1 | rm resource/logs/events*
2 |
--------------------------------------------------------------------------------
/jsuarez/todo.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/jsuarez/todo.txt
--------------------------------------------------------------------------------
/jsuarez/tools/ColorEnts.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 | from sim.lib.Enums import Neon
4 | from tools.Colors import hex2rgb
5 | from scipy.misc import imread, imsave
6 | from matplotlib import pyplot as plt
7 |
8 | fDir = 'resource/Entity/'
9 | fName = 'neural'
10 | extension = '.png'
11 | neural = imread(fDir + fName + extension)
12 |
13 | inds = [(5, 13), (5, 14), (6, 13), (6, 14),
14 | (9, 9), (9, 10), (10, 9), (10, 10),
15 | (13, 13), (13, 14), (14, 13), (14, 14)]
16 | #px = [neural[r, c] for r, c in inds]
17 |
18 | for color in Neon:
19 | if color not in (Neon.RED, Neon.ORANGE, Neon.YELLOW, Neon.GREEN,
20 | Neon.MINT, Neon.CYAN, Neon.BLUE, Neon.PURPLE, Neon.MAGENTA,
21 | Neon.FUCHSIA, Neon.SPRING, Neon.SKY):
22 | continue
23 | name, val = color.name, hex2rgb(color.value)
24 |
25 | for r, c in inds:
26 | neural[r, c, :] = val
27 |
28 | f = fDir + fName + name + extension
29 | imsave(f, neural)
30 |
--------------------------------------------------------------------------------
/jsuarez/tools/ColorTransform.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 | from scipy.misc import imread, imsave
4 | from sim.lib.Enums import Neon
5 | from skimage.color import rgb2lab, deltaE_cie76
6 |
7 | fdir = 'resource/Material/'
8 | fname = 'textures.png'
9 | tex = imread(fdir+fname)
10 | colors = (
11 | Neon.RED, Neon.ORANGE, Neon.YELLOW,
12 | Neon.GREEN, Neon.MINT, Neon.CYAN,
13 | Neon.BLUE, Neon.PURPLE, Neon.MAGENTA,
14 | Neon.FUCHSIA, Neon.SPRING, Neon.SKY,
15 | Neon.BLOOD, Neon.BROWN, Neon.GOLD, Neon.SILVER)
16 | colors = np.stack([Neon.rgb(c) for c in colors])
17 | sz = tex.shape[0]
18 | alpha = tex[:, :, 3]
19 | tex = tex[:, :, :3]
20 |
21 | tex = tex.reshape(-1, 1, 3)
22 | tex = rgb2lab(tex/255)
23 |
24 | clrs = colors.reshape(1, -1, 3)
25 | clrs = rgb2lab(clrs/255)
26 |
27 | dists = deltaE_cie76(tex, clrs)
28 | #dists = np.sum((tex - clrs)**2, 2)
29 | inds = np.argmin(dists, 1)
30 | px = np.array([colors[i] for i in inds])
31 | px = px.reshape(sz, sz, 3)
32 | imsave('tex.png', px)
33 |
34 |
--------------------------------------------------------------------------------
/jsuarez/tools/Colors.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from matplotlib import pyplot as plt
3 | import numpy as np
4 |
5 | def hex2rgb(h):
6 | h = h.lstrip('#')
7 | return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
8 |
9 | class Neon:
10 | RED = '#ff0000'
11 | ORANGE = '#ff8000'
12 | YELLOW = '#ffff00'
13 |
14 | GREEN = '#00ff00'
15 | MINT = '#00ff80'
16 | CYAN = '#00ffff'
17 |
18 | BLUE = '#0000ff'
19 | PURPLE = '#8000ff'
20 | MAGENTA = '#ff00ff'
21 |
22 | WHITE = '#ffffff'
23 | GRAY = '#666666'
24 | BLACK = '#000000'
25 |
26 | BLOOD = '#bb0000'
27 | BROWN = '#7a3402'
28 | GOLD = '#eec600'
29 | SILVER = '#b8b8b8'
30 |
31 | FUCHSIA = '#ff0080'
32 | SPRING = '#80ff80'
33 | SKY = '#0080ff'
34 | TERM = '#41ff00'
35 |
36 | if __name__ == '__main__':
37 | colors = np.array([
38 | [Neon.RED, Neon.ORANGE, Neon.YELLOW, Neon.BLOOD, Neon.FUCHSIA],
39 | [Neon.GREEN, Neon.MINT, Neon.CYAN, Neon.BROWN, Neon.SPRING],
40 | [Neon.BLUE, Neon.PURPLE, Neon.MAGENTA, Neon.GOLD, Neon.SKY],
41 | [Neon.BLACK, Neon.GRAY, Neon.WHITE, Neon.SILVER, Neon.TERM]])
42 |
43 |
44 | sz = 64
45 | R, C = colors.shape
46 | img = np.zeros((R*sz, C*sz, 3), dtype=np.uint8)
47 | for r in range(R):
48 | for c in range(C):
49 | color = hex2rgb(colors[r][c])
50 | tile = np.zeros((sz, sz, 3)) + color
51 | img[r*sz:(r+1)*sz, c*sz:(c+1)*sz, :] = tile
52 |
53 | plt.imshow(img)
54 | plt.show()
55 |
--------------------------------------------------------------------------------
/jsuarez/tools/RayTest.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 | import ray
4 | import time
5 |
6 | ray.init()
7 |
8 | def timeit(f):
9 | def profile(*args, iters=1000):
10 | sumTime = 0
11 | for i in range(iters):
12 | start = time.time()
13 | f(*args)
14 | sumTime += time.time() - start
15 | print(sumTime/iters)
16 | return profile
17 |
18 | @timeit
19 | def rayShared(x):
20 | #xId = ray.put(x)
21 | return ray.get(x)
22 |
23 | @ray.remote
24 | class Foo:
25 | def __init__(self):
26 | pass
27 |
28 | def bar(self):
29 | return 1
30 |
31 | '''
32 | foo = Foo.remote()
33 | start = time.time()
34 | for i in range(1000):
35 | a = foo.bar.remote()
36 | print(time.time() - start)
37 | '''
38 |
39 |
40 | times = []
41 | x = np.random.rand(15000, 15000)
42 | x = ray.put(x)
43 | #noise = [str(np.random.rand())*int(sz)]
44 | rayShared(x, iters=1000)
45 |
46 | '''
47 | @ray.remote
48 | class Foo(object):
49 | def method(self):
50 | return 1
51 |
52 | a = Foo.remote()
53 | start = time.time()
54 | for i in range(1000):
55 | ray.get(a.method.remote()) # This also takes about 440us for me (on my laptop)
56 | print(time.time()-start)
57 | '''
58 |
--------------------------------------------------------------------------------
/jsuarez/tools/SeedTest.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import numpy as np
3 | import ray
4 | import torch
5 | from torch import nn
6 |
7 |
8 | @ray.remote
9 | def foo(i):
10 | np.random.seed(i)
11 | torch.manual_seed(i)
12 | fc = nn.Sequential(nn.Linear(2, 2))
13 | print(i, ': ', [e for e in fc.parameters()][0])
14 |
15 | ray.init()
16 | jobs = [foo.remote(i) for i in range(5)]
17 | print(ray.get(jobs))
18 |
19 |
20 |
--------------------------------------------------------------------------------
/jsuarez/tools/TensorboardExample.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import tensorflow as tf
3 | import numpy as np
4 | import time
5 |
6 |
7 | class Logger:
8 | def __init__(self):
9 | self.writer = tf.summary.FileWriter("./logdir")
10 |
11 | def log(self, val, tag):
12 | summary = tf.Summary(value=[tf.Summary.Value(
13 | tag=tag, simple_value=val)])
14 | self.writer.add_summary(summary)
15 |
16 | i = 0
17 | logger = Logger()
18 | while True:
19 | i += 1
20 | s = np.sin(i/100)
21 | logger.log(s, 'sin')
22 | logger.log(np.log(i), 'log')
23 |
24 | if i % 30 == 0:
25 | print(s)
26 |
27 | time.sleep(0.01)
28 |
29 | # while the above is running, execute
30 | # tensorboard --logdir ./logdir
31 |
32 |
--------------------------------------------------------------------------------
/jsuarez/tools/TestDropbox.py:
--------------------------------------------------------------------------------
1 | from sim.lib import MPIUtils
2 |
3 | def packets():
4 | return [i for i in range(10000)]
5 |
6 | class Client:
7 | def __init__(self, server):
8 | self.server = server
9 |
10 | def step(self):
11 | MPIUtils.print(MPIUtils.ALL, 'Client Recv')
12 | packets = MPIUtils.recv(self.server, usePar=True)
13 | MPIUtils.print(MPIUtils.ALL, 'Client Send')
14 | MPIUtils.isend(packets, self.server, tag=MPIUtils.core())
15 |
16 | class Server:
17 | def __init__(self, clients):
18 | self.clients = clients
19 |
20 | def map(self):
21 | MPIUtils.print(MPIUtils.ALL, 'Server Send')
22 | for worker in self.clients:
23 | MPIUtils.print(MPIUtils.ALL, 'Server Send')
24 | for pack in packets():
25 | MPIUtils.isend(pack, worker, tag=worker)
26 |
27 | def reduce(self):
28 | reqs = []
29 | for client in self.clients:
30 | MPIUtils.print(MPIUtils.ALL, 'Server Recv')
31 | reqs.append(MPIUtils.irecv(client, tag=client))
32 | for req in reqs:
33 | req.wait()
34 |
35 |
36 | def test():
37 | if MPIUtils.core() == MPIUtils.MASTER:
38 | server = Server([1])
39 | else:
40 | client = Client(0)
41 | while True:
42 | if MPIUtils.core() == MPIUtils.MASTER:
43 | server.map()
44 | elif MPIUtils.core() == 1:
45 | client.step()
46 | if MPIUtils.core() == MPIUtils.MASTER:
47 | server.reduce()
48 |
49 | if __name__ == '__main__':
50 | test()
51 |
--------------------------------------------------------------------------------
/jsuarez/tools/TestGA.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from torch import nn
3 | from torch.autograd import Variable
4 |
5 | from copy import deepcopy
6 | import numpy as np
7 | from pdb import set_trace as T
8 |
9 | def var(xNp, volatile=False, cuda=False):
10 | x = Variable(torch.from_numpy(xNp), volatile=volatile).float()
11 | if cuda:
12 | x = x.cuda()
13 | return x
14 |
15 | class StimNet(nn.Module):
16 | def __init__(self, xdim, h, ydim):
17 | super().__init__()
18 | self.fc1 = torch.nn.Linear(xdim, h)
19 | self.fc2 = torch.nn.Linear(h, ydim)
20 |
21 | def forward(self, x):
22 | a = self.fc1(x)
23 | a = torch.nn.functional.relu(a)
24 | a = self.fc2(a)
25 | return a
26 |
27 | def randomMutation(ann, sigma):
28 | annNew = deepcopy(ann)
29 | for e in annNew.parameters():
30 | e.data = e.data + torch.Tensor(sigma*np.random.randn(*e.size()))
31 | return annNew
32 |
33 | def GA(fitness, generations, n, t, sigma, dims):
34 | P, F = [], []
35 | for g in range(generations):
36 | Pn, Fn = [], []
37 | for i in range(n):
38 | if g == 0:
39 | P.append(StimNet(*dims))
40 | F.append(fitness(P[-1]))
41 | elif i == 0:
42 | Pn.append(P[0])
43 | Fn.append(F[0])
44 | else:
45 | k = np.random.randint(0, t)
46 | Pn.append(randomMutation(P[k], sigma))
47 | Fn.append(fitness(Pn[-1]))
48 | #Sort dec by F
49 | if g > 0:
50 | inds = np.argsort(Fn)[::-1]
51 | F = np.asarray(Fn)[inds].tolist()
52 | P = np.asarray(Pn)[inds].tolist()
53 | print(F[0])
54 |
55 | if __name__ == '__main__':
56 | generations = 100
57 | n = 1000
58 | t = 10
59 | sigma = 0.01
60 | dims = (847, 16, 6)
61 |
62 | def fitness(ann):
63 | inp = var(np.random.randn(dims[0]))
64 | out = ann(inp)
65 | loss = -torch.sum((1 - out)**2)
66 | return loss.data[0]
67 |
68 | ret = GA(fitness, generations, n, t, sigma, dims)
69 |
--------------------------------------------------------------------------------
/jsuarez/tools/Tests.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from sim import Exchange
3 | from sim.item import RawFish
4 |
5 | def testExchange():
6 | market = Exchange.Exchange()
7 | sardine = RawFish.Sardine
8 |
9 | def checkPrint():
10 | print(market.buyOffers[sardine].queue)
11 | print(market.sellOffers[sardine].queue)
12 | print()
13 |
14 | market.buy(sardine, 1, 90)
15 | checkPrint()
16 | market.sell(sardine, 2, 100)
17 | checkPrint()
18 | market.buy(sardine, 3, 130)
19 | checkPrint()
20 | market.sell(sardine, 5, 90)
21 | checkPrint()
22 | market.buy(sardine, 5, 100)
23 | checkPrint()
24 |
25 | if __name__ == '__main__':
26 | testExchange()
27 |
--------------------------------------------------------------------------------
/jsuarez/tools/VideoLog.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | import cv2
3 | import numpy as np
4 | from scipy.misc import imresize
5 |
6 | framedir = 'resource/data/'
7 | prefixes = 'sl ml ll sr mr lr'.split()
8 | suffixes = [str(i) for i in range(250)]
9 | sz = 1024
10 | fNames, frames = [], []
11 | for suf in suffixes:
12 | print(suf)
13 | fName = framedir + 'slframe' + suf + '.png'
14 | sl = cv2.imread(fName, cv2.IMREAD_COLOR)[:256, :256, :]
15 | sl = imresize(sl, (sz, sz))
16 |
17 | fName = framedir + 'srframe' + suf + '.png'
18 | sr = cv2.imread(fName, cv2.IMREAD_COLOR)[:256, :256, :]
19 | sr = imresize(sr, (sz, sz))
20 |
21 | fName = framedir + 'mlframe' + suf + '.png'
22 | ml = cv2.imread(fName, cv2.IMREAD_COLOR)[:512, :512, :]
23 | ml = imresize(ml, (sz, sz))
24 |
25 | fName = framedir + 'mrframe' + suf + '.png'
26 | mr = cv2.imread(fName, cv2.IMREAD_COLOR)[:512, :512, :]
27 | mr = imresize(mr, (sz, sz))
28 |
29 | fName = framedir + 'llframe' + suf + '.png'
30 | ll = cv2.imread(fName, cv2.IMREAD_COLOR)[:1024, :1024, :]
31 | ll = imresize(ll, (sz, sz))
32 |
33 | fName = framedir + 'lrframe' + suf + '.png'
34 | lr = cv2.imread(fName, cv2.IMREAD_COLOR)[:1024, :1024, :]
35 | lr = imresize(lr, (sz, sz))
36 |
37 | l = np.concatenate((sl, ml, ll), axis=1)
38 | r = np.concatenate((sr, mr, lr), axis=1)
39 | frame = np.concatenate((l, r), axis=0)
40 | frame = np.stack((frame[:,:,2], frame[:,:,1], frame[:,:,0]), axis=2)
41 | frames.append(frame)
42 |
43 | import imageio
44 | imageio.mimwrite('godsword.mp4', frames, fps = 6)
45 |
46 |
--------------------------------------------------------------------------------
/jsuarez/tools/codesize.sh:
--------------------------------------------------------------------------------
1 | find . -name "*.py" -type f -exec grep . {} \; | wc -l
2 |
--------------------------------------------------------------------------------
/jsuarez/tools/handletest.py:
--------------------------------------------------------------------------------
1 | import ray
2 |
3 | ray.init(driver_mode=ray.PYTHON_MODE)
4 |
5 | @ray.remote
6 | class Actor1:
7 | def method(self):
8 | pass
9 |
10 | @ray.remote
11 | class Actor2:
12 | def __init__(self, a):
13 | self.a = a
14 | def method(self):
15 | ray.get(self.a.method.remote())
16 |
17 | a1 = Actor1.remote()
18 | a2 = Actor2.remote(a1)
19 | ray.get(a2.method.remote())
20 |
--------------------------------------------------------------------------------
/jsuarez/tools/test.py:
--------------------------------------------------------------------------------
1 | from pdb import set_trace as T
2 | from kivy.app import App
3 | from kivy.uix.widget import Widget
4 | from kivy.graphics import Rectangle, Color
5 |
6 | class CornerRectangleWidget(Widget):
7 | def __init__(self, **kwargs):
8 | super(CornerRectangleWidget, self).__init__(**kwargs)
9 |
10 | with self.canvas:
11 | Color(1, 0, 0, 1) # set the colour to red
12 | self.rect = Rectangle(pos=self.center,
13 | size=(self.width/2.,
14 | self.height/2.))
15 |
16 | class MyApp(App):
17 | def build(self):
18 | game = CornerRectangleWidget()
19 | #Clock.schedule_interval(game.update, 1.0/1000.0)
20 | return game
21 |
22 | if __name__ == '__main__':
23 | MyApp().run()
24 |
--------------------------------------------------------------------------------
/logs.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import sys
3 | import json
4 | from pdb import set_trace as T
5 | from collections import defaultdict
6 | from matplotlib import pyplot as plt
7 | from forge.blade.lib.enums import Neon
8 |
9 | def plot(data, inds=None, label='data', c=Neon.RED.norm, lw=3):
10 | if inds is None:
11 | inds = np.arange(len(data))
12 | plt.plot(inds, data, c=c, linewidth=lw, label=label)
13 |
14 | def dark():
15 | plt.style.use('dark_background')
16 |
17 | def labels(xlabel='x', ylabel='y', title='title',
18 | axsz=24, titlesz=28):
19 | plt.xlabel(xlabel, fontsize=axsz)
20 | plt.ylabel(ylabel, fontsize=axsz)
21 | plt.title(title, fontsize=titlesz)
22 |
23 | def axes(ac, tc):
24 | ax = plt.gca()
25 | ax.title.set_color(ac)
26 | ax.xaxis.label.set_color(ac)
27 | ax.yaxis.label.set_color(ac)
28 | for spine in ax.spines.values():
29 | spine.set_color(tc)
30 |
31 | def limits(xlims=None, ylims=None):
32 | if xlims is not None:
33 | plt.xlim(*xlims)
34 |
35 | if ylims is not None:
36 | plt.ylim(*ylims)
37 |
38 | def ticks(ts, tc):
39 | ax = plt.gca()
40 | ax.tick_params(axis='x', colors=tc)
41 | ax.tick_params(axis='y', colors=tc)
42 | for tick in ax.xaxis.get_major_ticks():
43 | tick.label1.set_fontsize(ts)
44 | tick.label1.set_fontweight('bold')
45 | for tick in ax.yaxis.get_major_ticks():
46 | tick.label1.set_fontsize(ts)
47 | tick.label1.set_fontweight('bold')
48 |
49 | def legend(ts, tc):
50 | leg = plt.legend(loc='upper right')
51 | for text in leg.get_texts():
52 | plt.setp(text, color=tc)
53 | plt.setp(text, fontsize=ts)
54 |
55 | def fig():
56 | fig = plt.gcf()
57 | fig.set_size_inches(12, 8, forward=True)
58 | #plt.tight_layout()
59 |
60 | def show():
61 | fig.canvas.set_window_title('Projekt Godsword')
62 |
63 | def save(fPath):
64 | fig = plt.gcf()
65 | fig.savefig(fPath, dpi=300)
66 |
67 | def load(fDir):
68 | try:
69 | with open(fDir, 'r') as f:
70 | logs = json.load(f)
71 |
72 | logDict = defaultdict(list)
73 | for log in logs:
74 | for k, v in log.items():
75 | logDict[k].append(v)
76 | return logDict
77 | except Exception as e:
78 | print(e)
79 | return None
80 |
81 | def godsword():
82 | labels('Steps', 'Value', 'Projekt: Godsword')
83 | axes(Neon.MINT.norm, Neon.CYAN.norm)
84 | ticks(18, Neon.CYAN.norm)
85 | legend(18, Neon.CYAN.norm)
86 | fig()
87 |
88 | def plots(logs):
89 | colors = Neon.color12()
90 | logs = reversed([e for e in logs.items()])
91 | for idx, kv in enumerate(logs):
92 | k, v = kv
93 | color = colors[idx].norm
94 | plot(v, k, color)
95 |
96 | def log():
97 | fDir = 'resource/logs/'
98 | fName = 'frag.png'
99 | logs = load(fDir + 'logs.json')
100 | dark()
101 | plots(logs)
102 | plt.ylim(0, 150)
103 | godsword()
104 | save(fDir+fName)
105 | plt.close()
106 |
107 |
--------------------------------------------------------------------------------
/resource/assets/action/mage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/action/mage.png
--------------------------------------------------------------------------------
/resource/assets/action/mageattack.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/action/mageattack.png
--------------------------------------------------------------------------------
/resource/assets/action/melee.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/action/melee.png
--------------------------------------------------------------------------------
/resource/assets/action/meleeattack.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/action/meleeattack.png
--------------------------------------------------------------------------------
/resource/assets/action/range.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/action/range.png
--------------------------------------------------------------------------------
/resource/assets/action/rangeattack.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/action/rangeattack.png
--------------------------------------------------------------------------------
/resource/assets/entity/chicken.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/chicken.png
--------------------------------------------------------------------------------
/resource/assets/entity/goblin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/goblin.png
--------------------------------------------------------------------------------
/resource/assets/entity/neural.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neural.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralBLUE.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralBLUE.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralCYAN.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralCYAN.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralFUCHSIA.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralFUCHSIA.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralGREEN.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralGREEN.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralMAGENTA.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralMAGENTA.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralMINT.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralMINT.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralORANGE.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralORANGE.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralPURPLE.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralPURPLE.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralRED.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralRED.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralSKY.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralSKY.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralSPRING.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralSPRING.png
--------------------------------------------------------------------------------
/resource/assets/entity/neuralYELLOW.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/entity/neuralYELLOW.png
--------------------------------------------------------------------------------
/resource/assets/fonts/dragonslapper.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/fonts/dragonslapper.ttf
--------------------------------------------------------------------------------
/resource/assets/splash/splash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/splash/splash.png
--------------------------------------------------------------------------------
/resource/assets/tiles/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/.DS_Store
--------------------------------------------------------------------------------
/resource/assets/tiles/brick.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/brick.png
--------------------------------------------------------------------------------
/resource/assets/tiles/clay.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/clay.png
--------------------------------------------------------------------------------
/resource/assets/tiles/coal_ore.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/coal_ore.png
--------------------------------------------------------------------------------
/resource/assets/tiles/cobblestone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/cobblestone.png
--------------------------------------------------------------------------------
/resource/assets/tiles/dirt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/dirt.png
--------------------------------------------------------------------------------
/resource/assets/tiles/forest.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/forest.png
--------------------------------------------------------------------------------
/resource/assets/tiles/grass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/grass.png
--------------------------------------------------------------------------------
/resource/assets/tiles/grass_side.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/grass_side.png
--------------------------------------------------------------------------------
/resource/assets/tiles/gravel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/gravel.png
--------------------------------------------------------------------------------
/resource/assets/tiles/ice.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/ice.png
--------------------------------------------------------------------------------
/resource/assets/tiles/iron_ore.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/iron_ore.png
--------------------------------------------------------------------------------
/resource/assets/tiles/lava.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/lava.png
--------------------------------------------------------------------------------
/resource/assets/tiles/lavaold.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/lavaold.png
--------------------------------------------------------------------------------
/resource/assets/tiles/planks_oak.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/planks_oak.png
--------------------------------------------------------------------------------
/resource/assets/tiles/sand.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/sand.png
--------------------------------------------------------------------------------
/resource/assets/tiles/sandstone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/sandstone.png
--------------------------------------------------------------------------------
/resource/assets/tiles/scrub.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/scrub.png
--------------------------------------------------------------------------------
/resource/assets/tiles/snow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/snow.png
--------------------------------------------------------------------------------
/resource/assets/tiles/stone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/stone.png
--------------------------------------------------------------------------------
/resource/assets/tiles/tree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/tree.png
--------------------------------------------------------------------------------
/resource/assets/tiles/water.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/assets/tiles/water.png
--------------------------------------------------------------------------------
/resource/docs/ags.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/ags.png
--------------------------------------------------------------------------------
/resource/docs/air.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/air.png
--------------------------------------------------------------------------------
/resource/docs/air_thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/air_thumbnail.png
--------------------------------------------------------------------------------
/resource/docs/early_demo.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/early_demo.mp4
--------------------------------------------------------------------------------
/resource/docs/earth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/earth.png
--------------------------------------------------------------------------------
/resource/docs/earth_thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/earth_thumbnail.png
--------------------------------------------------------------------------------
/resource/docs/env.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/env.jpg
--------------------------------------------------------------------------------
/resource/docs/equipment.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/equipment.png
--------------------------------------------------------------------------------
/resource/docs/fire.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/fire.png
--------------------------------------------------------------------------------
/resource/docs/fire_thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/fire_thumbnail.png
--------------------------------------------------------------------------------
/resource/docs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/logo.png
--------------------------------------------------------------------------------
/resource/docs/logodark.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/logodark.png
--------------------------------------------------------------------------------
/resource/docs/map.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/map.png
--------------------------------------------------------------------------------
/resource/docs/neural.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neural.png
--------------------------------------------------------------------------------
/resource/docs/neuralBLUE.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralBLUE.png
--------------------------------------------------------------------------------
/resource/docs/neuralCYAN.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralCYAN.png
--------------------------------------------------------------------------------
/resource/docs/neuralFUCHSIA.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralFUCHSIA.png
--------------------------------------------------------------------------------
/resource/docs/neuralGREEN.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralGREEN.png
--------------------------------------------------------------------------------
/resource/docs/neuralMAGENTA.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralMAGENTA.png
--------------------------------------------------------------------------------
/resource/docs/neuralMINT.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralMINT.png
--------------------------------------------------------------------------------
/resource/docs/neuralORANGE.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralORANGE.png
--------------------------------------------------------------------------------
/resource/docs/neuralPURPLE.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralPURPLE.png
--------------------------------------------------------------------------------
/resource/docs/neuralRED.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralRED.png
--------------------------------------------------------------------------------
/resource/docs/neuralSKY.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralSKY.png
--------------------------------------------------------------------------------
/resource/docs/neuralSPRING.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralSPRING.png
--------------------------------------------------------------------------------
/resource/docs/neuralYELLOW.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/neuralYELLOW.png
--------------------------------------------------------------------------------
/resource/docs/quests.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/quests.png
--------------------------------------------------------------------------------
/resource/docs/skills.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/skills.png
--------------------------------------------------------------------------------
/resource/docs/water.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/water.png
--------------------------------------------------------------------------------
/resource/docs/water_thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/docs/water_thumbnail.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/model/bests.pth:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/model/bests.pth
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/counts_forest.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/counts_forest.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/counts_grass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/counts_grass.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/counts_scrub.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/counts_scrub.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/explore_grass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/explore_grass.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/explore_scrub.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/explore_scrub.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/lifetime.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/lifetime.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/reward.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/reward.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/unique_forest.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/unique_forest.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/unique_grass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/unique_grass.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/unique_scrub.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/unique_scrub.png
--------------------------------------------------------------------------------
/resource/exps/sample-autotarget/train/value.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/sample-autotarget/train/value.png
--------------------------------------------------------------------------------
/resource/exps/testchaos128/model/bests.pth:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/resource/exps/testchaos128/model/bests.pth
--------------------------------------------------------------------------------
/resource/logs/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore everything in this directory
2 | *
3 | # Except this file
4 | !.gitignore
5 |
--------------------------------------------------------------------------------
/resource/maps/procedural/.gitignore:
--------------------------------------------------------------------------------
1 | map*/
2 |
--------------------------------------------------------------------------------
/resource/maps/testtileset.tsx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/resource/maps/tiles.tsx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/resource/maps/tileset.tsx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/scripts/setup/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/scripts/setup/__init__.py
--------------------------------------------------------------------------------
/scripts/setup/requirements.txt:
--------------------------------------------------------------------------------
1 | autobahn==19.2.1
2 | cloudpickle==0.5.2
3 | matplotlib==2.1.2
4 | noise==1.2.2
5 | numpy==1.16.0
6 | opensimplex==0.2
7 | psutil==5.6.0
8 | PyTMX==3.21.5
9 | pygame==1.9.4
10 | ray==0.6.2
11 | redis==3.1.0
12 | torch==0.4.0
13 | torchvision==0.2.0
14 | Twisted==18.9.0
15 |
--------------------------------------------------------------------------------
/scripts/setup/setup.sh:
--------------------------------------------------------------------------------
1 | #Pytorch
2 | pip install http://download.pytorch.org/whl/cu90/torch-0.4.0-cp36-cp36m-linux_x86_64.whl
3 | pip install torchvision
4 |
5 | #Ray -- will segfault in .backward with wrong version
6 | #pip uninstall -y ray
7 | #pip install -U https://s3-us-west-2.amazonaws.com/ray-wheels/68b11c8251dc41e79dc9dc4b1da31630708a6bd8/ray-0.4.0-cp36-cp36m-manylinux1_x86_64.whl
8 |
9 | #Ray
10 | pip install ray
11 | pip install setproctitle
12 | pip install service_identity
13 |
14 | #Basics
15 | pip install numpy
16 | pip install scipy
17 | pip install matplotlib
18 |
19 |
20 | #Tiled map loader
21 | pip install pytmx
22 |
23 | #jsonpickle
24 | pip install jsonpickle
25 | pip install opensimplex
26 | pip install twisted
27 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #This fails on some systems
2 | #import os
3 | #os.system('scripts/setup/setup.sh')
4 |
5 | import terrain
6 |
--------------------------------------------------------------------------------
/v1.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openai/neural-mmo/38fd0310bc784de9b86e5144d0e78f4d31005e6b/v1.2.png
--------------------------------------------------------------------------------